摘自:http://www.itwis.com/html/net/c/20110411/10175.htmlhtml
C#泛型反射和普通反射的區別,泛型反射和普通反射的區別就是泛型參數的處理上
先看一個簡單的例子。
class Class1<T>
{
public void Test(T t)
{
Console.WriteLine(t);
}
}
要利用反射動態建立該類型實例,並調用 Test 方法,咱們能夠使用以下方法
Type type = typeof(Class1<int>);
object o = Activator.CreateInstance(type);
type.InvokeMember("Test", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, new object[] { 123 });
但若是泛型參數是未定的,咱們該如何處理呢?其實 Type 已經增長了相似的處理機制。
static void InvokeTest(Type t, params object[] args)
{
Type type = typeof(Class1<>);
type = type.MakeGenericType(t);
object o = Activator.CreateInstance(type);
type.InvokeMember("Test", BindingFlags.Default | BindingFlags.InvokeMethod, null, o, args);
}
另一種狀況就是泛型方法,
class Class1
{
public void Test<T>(T t)
{
Console.WriteLine(t);
}
}
方法相似,只不過這回使用的是 MethodInfo.MakeGenericMethod()
static void InvokeTest(Type t, params object[] args)
{
Type type = typeof(Class1);
object o = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("Test", BindingFlags.Instance | BindingFlags.Public);
method = method.MakeGenericMethod(t);
method.Invoke(o, args);
}htm
固然還有實例化一個泛型get
例若有GenericType<M,N>string
Type genericType = typeof(GenericType<>);it
Type[] templateTypeSet = new[] { typeof(string), typeof(int) };class
Type implementType = genericType.MakeGenericType( templateTypeSet );泛型
這樣 implementType類型就是賦予了string,int的泛型類了object