【问题标题】:How to return an IEnumerable of type X from a method如何从方法返回 X 类型的 IEnumerable
【发布时间】:2016-12-10 09:48:01
【问题描述】:

所以我想要实现的本质上是将一个类型传递给一个方法并从该方法返回一个该类型的 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,我想知道是否有办法返回一个类型为 Test 的 IEnumerable

提前致谢

【问题讨论】:

  • 为什么不使用泛型? IEnumerable&lt;Test&gt; x = PassType&lt;Test&gt;();
  • @TimSchmelter 我猜 OP 在编译时不知道类型。

标签: c# linq oop types


【解决方案1】:

实际上你返回的IEnumerable&lt;TheType&gt;,至少在运行时是这样。但是,您不能指望 编译器 推断您在 runtime 中提供的类型参数。因此编译器无法知道可枚举是哪种类型,它只知道它是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&lt;T&gt; 自.NET 4.0 起是协变的,如果您的所有类型都实现MyBaseClass,您可以将其转换为IEnumerable&lt;object&gt;IEnumerable&lt;MyBaseClass&gt;。但是您永远不会在编译时获得IEnumerable&lt;MyType&gt; 并直接在实例上调用该类型的成员。

【讨论】:

    【解决方案2】:

    我认为你应该看看 C# 中的泛型。

    更多信息:Generics

    【讨论】:

    • 您应该考虑将该文章中的相关信息写入您的答案或将此答案作为评论。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    相关资源
    最近更新 更多