[英]Casting an IEnumerable to IEnumerable<T> with reflection
因此,我需要调用具有这样签名的第三方方法
ThirdPartyMethod<T>(IEnumerable<T> items)
我的问题是我在编译时不知道对象的类型。
在编译时我有这个
IEnumerable myObject;
Type typeOfEnumerableIHave;
如此反射可以以某种方式帮助我吗?
为了简单起见,假装我有一个这样的方法
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()
:
ThirdPartyMethod(myObject.Cast<T>())
如果在编译时不知道T
类型,则应在运行时提供它。
考虑一下您的第三方库看起来像这样
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
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 }) });
您可以尝试这样的事情:
void DoWork(IEnumerable items, Type type)
{
// instance of object you want to call
var thirdPartyObject = new ThirdPartyObject();
// create a list with type "type"
var typeOfList = typeof(List<>).MakeGenericType(type);
// create an instance of the list and set items
// as constructor parameter
var listInstance = Activator.CreateInstance(listOfTypes, items);
// call the 3. party method via reflection, make it generic and
// provide our list instance as parameter
thirdPartyObject.GetType().GetMethod("ThirdPartyMethod")
.MakeGenericMethod(type)
.Invoke(thirdPartyObject, new []{listInstance});
}
该代码创建通用类型“类型”的列表实例(通过使用MakeGenericType)。 然后将您的item元素复制到列表中,并通过relection调用第三方方法(请注意“ MakeGenericMethod”调用,以确保该方法具有与方法参数相同的类型参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.