在c# 中,有时候需要用到反射区调用带有泛型的方法。如例子:
public string CheckReflection<T>(string propertyName, T propertyValue) where T : struct
{throw new InvalidOperationException(string.Format("Property {0} is not supported.", propertyName));
}
在调用这个方法的时候,需要System.Reflection.MethodInfo 和Activator
如下方法
private string CallByReflection(
object scanProcedure, // scanProcedure 是你要反射对象的实例
string propertyName, // 参数一
object propertyValue) // 参数二
{
Type type = scanProcedure.GetType();
object reflectTest = Activator.CreateInstance(type);
// Just for simplicity, assume it's public etc
MethodInfo method = typeof(反射的className).GetMethod("方法名"); //调用方法
MethodInfo generic = method.MakeGenericMethod(propertyValue.GetType());
return (string)generic.Invoke(reflectTest, new object[] { propertyName, propertyValue });
}