本文介绍了类型转换,是Cast< T>的运行时替代方案.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IList<object>,其中每个对象都是T类型的实例(我在编译时不知道).

I have an IList<object> where every single object is an instance of a type T (which I don't know at compile-time).

我需要一个IList<T>.我不能使用Cast,因为我在编译时不知道类型,并且没有可以使用的Cast(Type)重载.

I need an IList<T> out of this. I can't use Cast since I don't know the type at compile time, and there isn't a Cast(Type) overload I could use.

这是我目前所拥有的:

private object Map(IList<ApiCallContext> bulk)
{
    // god-awful way to build a IEnumerable<modelType> list out of Enumerable<object> where object is modelType.
    // quoting lead: "think whatever you do it will be ugly"
    Type modelType = model.Method.ModelType;

    if (bulk.Count > 0)
    {
        modelType = bulk.First().Parameters.GetType();
    }
    Type listType = typeof(List<>).MakeGenericType(modelType);
    object list = Activator.CreateInstance(listType);
    foreach (object value in bulk.Select(r => r.Parameters))
    {
        ((IList)list).Add(value);
    }
    return list;
}

我正在考虑的是,也许我可以创建一个实现IList的新LooseList类,并且该类可以在强制转换周围工作,似乎比我现在拥有的要好,但听起来仍然很笨拙.

What I'm thinking about is maybe I could create a new LooseList class that implements IList and just works around the casting, seems better than what I currently have but it still sounds way too clunky.

推荐答案

如果您确实确实需要按照您所说的去做,那么我首先将其分为特定于上下文的代码"和可重用的代码".实际上,您想要这样的东西:

If you really need to do exactly as you've stated, I'd first separate this out into "context-specific code" and "reusable code". Effectively you want something like this:

public static IList ToStrongList(this IEnumerable source, Type targetType)

我会通过写一个强类型方法实现,然后通过反射调用它:

I would implement that by writin a strongly-typed method, and then calling it via reflection:

private static readonly MethodInfo ToStrongListMethod = typeof(...)
    .GetMethod("ToStrongListImpl", BindingFlags.Static | BindingFlags.NonPublic);

public static IList ToStrongList(this IEnumerable source, Type targetType)
{
    var method = ToStrongListMethod.MakeGenericMethod(targetType);
    return (IList) method.Invoke(null, new object[] { source });
}

private static List<T> ToStrongListImpl<T>(this IEnumerable source)
{
    return source.Cast<T>().ToList();
}

这篇关于类型转换,是Cast&lt; T&gt;的运行时替代方案.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:15