Invoke a Static Method using Reflection
2011-06-15 07:20 叶伟民 阅读(534) 评论(0) 编辑 收藏 举报class
ClassWithGenericStaticMethod
{
public static void
PrintName<T>(string
prefix) where T :
class
{
Console.WriteLine(prefix + " " + typeof(T).FullName);
}
}
// Grabbing the type that has the static generic
method
Type typeofClassWithGenericStaticMethod =
typeof(ClassWithGenericStaticMethod);
// Grabbing the specific static method
MethodInfo methodInfo =
typeofClassWithGenericStaticMethod.GetMethod("PrintName", System.Reflection.BindingFlags.Static | BindingFlags.Public);
// Binding the method info to generic
arguments
Type[]
genericArguments = new
Type[] { typeof(Program)
};
MethodInfo genericMethodInfo =
methodInfo.MakeGenericMethod(genericArguments);
// Simply invoking the method and
passing parameters
// The null parameter is the object to call the method
from. Since the method is
// static, pass null.
object returnValue =
genericMethodInfo.Invoke(null, new object[] { "hello" });
本文来自博客园,作者:叶伟民,转载请注明原文链接:https://www.cnblogs.com/adalovelacer/archive/2011/06/15/2081119.html