c# - 将 IEnumerable 转换/转换为 IEnumerable<T>

标签 c# linq

我有一个类(Web 控件),它具有 IEnumerable 类型的属性,并且想使用 LINQ 处理参数。

有没有什么方法可以在编译时不知道类型的情况下通过反射将 IEnumerable 强制转换/转换/调用?

Method void (IEnumerable source)
{
    var enumerator = source.GetEnumerator();

    if (enumerator.MoveNext())
    {
        var type = enumerator.Current.GetType();
        Method2<type>(source); // this doesn't work! I know!
    }
}

void Method2<T>(IEnumerable<T> source) {}

最佳答案

你的Method2真的很关心它得到什么类型?如果没有,您可以调用 Cast<object>() :

void Method (IEnumerable source)
{
    Method2(source.Cast<object>());
}

如果您确实需要获得正确的类型,则需要使用反射。

类似于:

MethodInfo method = typeof(MyType).GetMethod("Method2");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, new object[] {source});

但这并不理想……特别是,如果源不是完全 IEnumerable<type>那么调用将失败。例如,如果第一个元素恰好是一个字符串,但源是一个 List<object> ,你会遇到问题。

关于c# - 将 IEnumerable 转换/转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/812673/

相关文章:

linq - 您见过的最严重的 LINQ 语法滥用是什么?

c# - 所有 GUI 线程的 Application.ThreadException 事件

c# - Naudio float Sample 和 Concentus.OggFile short Sample,将 mp3 转换为 opus ogg

c# - 如何在 Microsoft Bot 框架服务器端打开 Internet 选项卡?

c# - 如何删除 lambda 表达式的 Where 条件?

C# 匿名类型 foreach 循环,更好的方法吗?

c# - 重播功能和参数列表

c# - 获取 DLL 的函数列表

c# - ADO.NET Entity Framework ObjectContext - 缓存问题

c# - Linq to SQL 编写可翻译函数