C# 反射泛型
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);
//以上两句或写成 method.MakeGenericMethod(t).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的泛型类了
反射 如何调用重载方法?
public class Sample1 { private string _str1 = "我是属性1"; public string Str1 { get { return _str1; } } /// <summary> /// 显示 /// </summary> /// <param name="s"></param> /// <returns></returns> public string Display() { return "无参数方法"; } /// <summary> /// 显示 /// </summary> /// <param name="s"></param> /// <returns></returns> public string Display(string s) { return s + "————有参方法"; } }
MethodInfo mi = structType.GetMethod("Display",new Type[]{}); //取的方法描述
string result = (string)mi.Invoke(structInstance, null);
Console.WriteLine(result);
mi = structType.GetMethod("Display", new Type[] { typeof(String)}); //取的方法描述
result = (string)mi.Invoke(structInstance, new object[] { "a"});
Console.WriteLine(result);
浙公网安备 33010602011771号