在给定类型名称的情况下调用静态函数

时间:2013-08-05 13:59:31

标签: c# reflection static-methods

我有一个包含类型名称的字符串。我想在反射中获取类型,并调用静态方法。 我想尽可能简化代码。 像这样的东西:

public class MyClass {    
          static int foo() 
          {
             return 7;
          }; 
}

var MyClassType = Type.GetType("MyClass"); 
// your help here! 
int res = (MyClassType).foo();

谢谢!

2 个答案:

答案 0 :(得分:5)

您需要指定正确的绑定标志才能使其正常工作:

// NOTE: Use full name for "MyClass", incuding any namespaces.
var myClassType = Type.GetType("MyClass");
int res = (int)myClassType.GetMethod("foo", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);

答案 1 :(得分:0)

试试这样:

int res = Type.GetType("MyClassType").GetMethod("foo").Invoke(null, null);