我有一个类(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});
但这并不理想......特别是如果来源不是exactly an IEnumerable<type>
那么调用将会失败。例如,如果第一个元素恰好是字符串,但源是List<object>
,你就会遇到问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)