的方法既然你有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 }) });
在這方面你有這'IEnumerable的myObject的;?'你能表現出一點點你的代碼的 – BrunoLM 2014-10-28 01:05:10
@BrunoLM我加了一點,我不知道這是否會幫助或不 – 2014-10-28 01:09:40