5

如何通过向构造函数提供 System.Type 值来实例化 a List<Foo>or在运行时?List<Bar>这个问题必须回答很多次,但我找不到。

最终,我想做一个像这样的扩展方法:

public static IEnumerable<T> CreateEnumerable<T>(this System.Collections.IEnumerable list, Type type){
    var stuff = something;

    // magic happens to stuff where stuff becomes an IEnumerable<T> and T is of type 'type'

    return stuff as IEnumerable<T>;
}
4

4 回答 4

11

您可以List<>在运行时使用反射和MakeGenericType方法指定参数。

var typeParam = typeof(Foo);
var listType = typeof(List<>).MakeGenericType(typeParam);

然后使用Activator类实例化它

var list = Activator.CreateInstance(listType);

但是,如果您只想将 anIEnumerable变成 an IEnumerable<T>,则 Linq 已经有方法 (CastOfType) 来执行此操作:

IEnumerable untypedList = ...

var foos = untypedList.Cast<Foo>(); // May throw InvalidCastException
var bars = untypedList.OfType<Bar>();
于 2013-03-02T15:59:14.990 回答
0

您不能在逻辑上使Type type参数与< T >通用参数匹配。

扩展方法必须返回非泛型IEnumerable

有可能使这个语法IEnumerable实际上(在运行时)拥有一个泛型IEnumerable < That particular type > ,但执行您的扩展方法的用户程序员必须做出假设、检查和强制转换。

InvalidCastException请注意,如果您走这条路并且用户程序员不知道这些事情,您可能最终会遇到:)。

它是这样的:

public static class SomeExtensions {

    private static readonly MethodInfo methodDefOf_PrivateHelper = typeof(SomeExtensions)
        .GetMethod("PrivateHelper", 
                   BindingFlags.NonPublic | BindingFlags.Static, 
                   Type.DefaultBinder, 
                   new [] { typeof(System.Collections.IEnumerable) }, 
                   null);

    private static IEnumerable<T> PrivateHelper<T>(System.Collections.IEnumerable @this){
        foreach (var @object in @this)
            yield return (T)@object; // right here is were you can get the cast exception
    }

    public static System.Collections.IEnumerable DynamicCast(
        this System.Collections.IEnumerable @this,
        Type elementType
    ) {
        MethodInfo particularizedMethod = SomeExtensions.methodDefOf_PrivateHelper
            .MakeGenericMethod(elementType);

        object result = particularizedMethod.Invoke(null, new object[] { @this });
        return result as System.Collections.IEnumerable;
    }


}

以下是你如何使用它:

object[] someObjects = new object[] { "one", "two", "three" };
IEnumerable implicitlyCastedToEnumerable = someObjects;

Type unknownType = (DateTime.Now.Hour > 14) ? typeof(string) : typeof(int);

IEnumerable apparentlyNothingHappenedHere 
    = implicitlyCastedToEnumerable.DynamicCast(unknownType);

// if it's not after 14:00, then an exception would've jumped over this line and
// straight out the exit bracket or into some catch clause

// it it's after 14:00, then the apparentlyNothingHappenedHere enumerable can do this:
IEnumerable<string> asStrings = (IEnumerable<string>)apparentlyNothingHappenedHere;

// whereas the earlier would've cause a cast exception at runtime
IEnumerable<string> notGoingToHappen = (IEnumerable<string>)implicitlyCastedToEnumerable;
于 2013-03-02T16:16:14.070 回答
0

这可能会奏效

public static IEnumerable<T> CreateEnumerable<T>(this IEnumerable list, Type type) {
    var stuff=something;

    var temp=stuff;
    stuff=Array.CreateInstance(type, count) as T[]; 
    // copy elements to stuff
    return stuff as IEnumerable<T>;
}

但是,不能保证T是 type type。看签名CreateEnumerable<T>

public static IEnumerable<T> CreateEnumerable<T>(this IEnumerable list, Type type) 

没有T从参数来推断调用哪个泛型方法,也就是说,当你想调用它时需要指定一个类型参数。我认为这T是多余的,而是

public static IEnumerable CreateEnumerable(this IEnumerable list, Type type) {
    var stuff=something;

    var temp=stuff;
    stuff=Array.CreateInstance(type, count);
    // copy elements to stuff
    return stuff as IEnumerable;
}

请注意,我不知道count您想要什么。

于 2013-03-02T17:19:59.443 回答
0

您的扩展方法已经是通用的。只需调用构造函数。

var list = new List<T>();

如果您想将非泛型 IEnumerable 转换为泛型,System.Linq 中已经有相应的方法。

return list.Cast<T>();
于 2013-03-02T16:05:14.207 回答