第一部份:知道 泛型類型,但泛型參數需要動態的情況
先看一個簡單的例子。
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 });
若泛型參數是未定的,可采用如下方法:
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);
}
當然還有實例化一個泛型
例如有GenericType<M,N>
Type genericType = typeof(GenericType<>);
Type[] templateTypeSet = new[] { typeof(string), typeof(int) };
Type implementType = genericType.MakeGenericType( templateTypeSet );
這樣 implementType類型就是賦予了string,int的泛型類了
第二種部份:泛型類型及參數均需要動態指定的情況
Type entityType = typeof(T);
Assembly assy = Assembly.GetExecutingAssembly();
//注意:以下字符串中的`1表示泛型參數占位符個數,一個泛型參數則表示為:`1,多個泛型參數則表示為:`N;
string genericTypeAssyName = string.Format("{0}.{1}Repository`1", assy.GetName().Name,entityType.Name);
出處:http://www.zuowenjun.cn/post/2015/07/22/174.html
