泛型类如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
public class SampleClass<T>
{
public static void StaticMethod()
{
Console.WriteLine("In StaticMethod, type T is " + typeof(T));
}
public void NonstaticMethod()
{
Console.WriteLine("In NonstaticMethod, type T is " + typeof(T));
}
}
}
主程序如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
public static void Main(string[] args)
{
Test(typeof(string));
Console.ReadKey();
}
private static void Test(Type type)
{
// 根据传入的类型调用SampleClass中的方法
}
}
}
一种错误的写法是
{
Type sampleClassType = typeof(SampleClass<type>); // 错误!
// 反射调用静态方法
// ...
// 反射调用非静态方法
// ...
}
正确的写法如下
private static void Test(Type type)
{
Type sampleClassType = typeof(SampleClass<>).MakeGenericType(type);
// 反射调用静态方法
MethodInfo staticMethod = sampleClassType.GetMethod("StaticMethod");
staticMethod.Invoke(null, null); // 静态方法调用不需要类实例,第一个参数为null
// 反射调用非静态方法
MethodInfo nonstaticMethod = sampleClassType.GetMethod("NonstaticMethod");
ConstructorInfo constructor = sampleClassType.GetConstructor(Type.EmptyTypes);
object obj = constructor.Invoke(null); // 构造SampleClass<>的实例
nonstaticMethod.Invoke(obj, null); // 非静态方法调用需要类实例
}
运行截图