我有一个类(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/