将IEnumerable转换为IEnumerable T用反射 [英] Casting an IEnumerable to IEnumerable<T> with reflection
问题描述
因此,我需要调用第三方方法,该方法具有这样的签名
So, I need to call a third party method, that has a signature like this
ThirdPartyMethod<T>(IEnumerable<T> items)
我的问题是我在编译时不知道对象的类型.
My problem is I don't know the type of my object at compile time.
在编译时我有这个
IEnumerable myObject;
Type typeOfEnumerableIHave;
Sooo ..反射可以以某种方式帮助我吗?
Sooo..can reflection help me out here somehow?
为简单起见,假装我有一个像这样的方法
for simplicity sake, pretend I have a method like this
void DoWork(IEnumerable items, Type type)
{
//In here I have to call ThirdPartyMethod<T>(IEnumerable<T> items);
}
推荐答案
由于具有IEnumerable myObject;
和像ThirdPartyMethod<T>(IEnumerable<T> items)
这样的签名,因此可以使用Cast()
:
Since you have IEnumerable myObject;
and signature like ThirdPartyMethod<T>(IEnumerable<T> items)
you are able to use Cast()
:
ThirdPartyMethod(myObject.Cast<T>())
如果在编译时不知道T
类型,则应在运行时提供它.
If you don't know the T
type at the compile time you should provide it at runtime.
考虑您的第三方库如下
public static class External
{
public static void ThirdPartyMethod<T>(IEnumerable<T> items)
{
Console.WriteLine(typeof(T).Name);
}
}
如果您关注
Type theType = typeof(int);
IEnumerable myObject = new object[0];
您可以在运行时获取通用方法ThirdPartyMethod
和Cast
you can get generic methods ThirdPartyMethod
and Cast
at the runtime
var targetMethod = typeof(External).GetMethod("ThirdPartyMethod", BindingFlags.Static | BindingFlags.Public);
var targetGenericMethod = targetMethod.MakeGenericMethod(new Type[] { theType });
var castMethod = typeof(Enumerable).GetMethod("Cast", BindingFlags.Static | BindingFlags.Public);
var caxtGenericMethod = castMethod.MakeGenericMethod(new Type[] { theType });
最后,您调用方法:
targetGenericMethod.Invoke(null, new object[] { caxtGenericMethod.Invoke(null, new object[] { myObject }) });
这篇关于将IEnumerable转换为IEnumerable T用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!