更新时间:2023-02-14 10:56:13
贵方法2
真正关心它得到什么类型?如果没有,你可能只需要调用演员LT;对象>()
:
void方法(IEnumerable的源)
{
方法2(source.Cast&所述;对象>());
}
如果你一定要得到正确的类型,你需要使用反射。
是这样的:
MethodInfo的方法= typeof运算(的MyType).GetMethod(方法2);
MethodInfo的通用= method.MakeGenericMethod(类型);
generic.Invoke(这一点,新的对象[] {源});
这不是理想的,虽然...特别是,如果源不是的究竟的一个的IEnumerable<类型>
则调用将失败。例如,如果第一个元素恰好是一个字符串,但来源是列表与LT;对象>
,你就会有问题。
I have a class (A web control) that has a property of type IEnumerable and would like to work with the parameter using LINQ.
Is there any way to cast / convert / invoke via reflection to IEnumerable<T> not knowing the type at compile time?
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) {}
Does your Method2
really care what type it gets? If not, you could just call Cast<object>()
:
void Method (IEnumerable source)
{
Method2(source.Cast<object>());
}
If you definitely need to get the right type, you'll need to use reflection.
Something like:
MethodInfo method = typeof(MyType).GetMethod("Method2");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, new object[] {source});
It's not ideal though... in particular, if source isn't exactly an IEnumerable<type>
then the invocation will fail. For instance, if the first element happens to be a string, but source is a List<object>
, you'll have problems.