Invoke a Static Method using Reflection

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" });

posted on 2011-06-15 07:20 叶伟民 阅读(56) 评论(0) 编辑 收藏

<2011年6月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

导航

统计

公告

www.1and1.com
===========华丽的分隔线==============
昵称:叶伟民
园龄:4年4个月
粉丝:21
关注:3

搜索

 
 

常用链接

我的标签

随笔分类

随笔档案

最新评论

阅读排行榜

评论排行榜

推荐排行榜