使用反射将IEnumerable转换为IEnumerable <T>

Kyl*_*bel 0 c# reflection ienumerable

所以,我需要调用第三方方法,它有这样的签名

ThirdPartyMethod<T>(IEnumerable<T> items)

我的问题是我在编译时不知道我的对象的类型.

在编译时我有这个

IEnumerable myObject;
Type typeOfEnumerableIHave;
Run Code Online (Sandbox Code Playgroud)

Sooo ..反思可以帮我解决这个问题吗?

为简单起见,假装我有这样的方法

void DoWork(IEnumerable items, Type type)
{
   //In here I have to call ThirdPartyMethod<T>(IEnumerable<T> items);
}
Run Code Online (Sandbox Code Playgroud)

Dil*_*ser 5

既然您拥有IEnumerable myObject;和签名就像ThirdPartyMethod<T>(IEnumerable<T> items)您可以使用Cast():

ThirdPartyMethod(myObject.Cast<T>())
Run Code Online (Sandbox Code Playgroud)

如果您T在编译时不知道类型,则应在运行时提供它.

考虑你第三方库看起来像这样

public static class External
{
    public static void ThirdPartyMethod<T>(IEnumerable<T> items)
    {
        Console.WriteLine(typeof(T).Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你有以下

Type theType = typeof(int); 
IEnumerable myObject = new object[0];
Run Code Online (Sandbox Code Playgroud)

你可以得到通用的方法,ThirdPartyMethodCast在运行时

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 });
Run Code Online (Sandbox Code Playgroud)

最后你调用方法:

targetGenericMethod.Invoke(null, new object[] { caxtGenericMethod.Invoke(null, new object[] { myObject }) });
Run Code Online (Sandbox Code Playgroud)