如何从方法返回类型X的IEnumerable

问题描述:

所以我想实现的基本上是将类型传递给方法,并从方法返回该类型的IEnumerable。如何从方法返回类型X的IEnumerable

这是我迄今管理:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var x = PassType(typeof(Test)); 
    } 

    public static IEnumerable<dynamic> PassType(Type destType) 
    { 
     var testInstance = new Test() { Name = "Greg", Age = 45, IsSomething = false }; 
     var destinationList = ((IEnumerable<object>)Activator.CreateInstance(typeof(List<>).MakeGenericType(new[] { destType }))).ToList(); 
     destinationList.Add(testInstance); 
     return destinationList; 
    } 
} 
public class Test 
{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public bool IsSomething { get; set; } 

    public Test() 
    { 

    } 
} 

然而,这显然是返回类型的IEnumerable动态的,我想知道是否有办法返回类型测试的IEnumerable

在此先感谢

+2

为什么不使用泛型? 'IEnumerable x = PassType ();' –

+0

@TimSchmelter我猜OP在编译时不知道类型。 – HimBromBeere

其实返回什么IEnumerable<TheType>,在运行时至少。但是你不能指望编译器推断你提供的类型参数att 运行时。因此编译器不知道枚举类型是什么类型,它只知道它是dynamic。这就是为什么你不能在枚举中的实例上调用该类型的任何成员。

然而,在你的情况下,简单的通用方法会做你想要什么:

var x = PassType<Test>(); 

这就需要你的方法与此类似:

IEnumerable<T> PassType<T>() { ...} 

如果您鸵鸟政策知道该类型在编译时您可以使用MakeGenericMethod通过在运行时传递的类型参数调用泛型方法:

var theMethod = typeof(Program).GetMethod("PassType").MakeGenericMethod(typeof(Test)); 
var x = theMethod.Invoke(); 

但是在编译期间,您仍然不知道类型,因此x的类型为object。由于IEnumerable<T>自.NET 4.0起协变,因此如果您的所有类型都实现了MyBaseClass,则可以将其转换为IEnumerable<object>IEnumerable<MyBaseClass>。但是编译时你永远不会得到IEnumerable<MyType>,并直接在实例上调用该类型的成员。

+0

这很有效,非常感谢 – ASMoncrieff

我想你应该看看泛型在C#中。

更多信息:Generics

+0

您应该考虑将该文章的相关信息写入您的答案或对此答案发表评论。 – HimBromBeere