2011-03-29 241 views
28

如何在类名作为字符串传递时使用反射来获取所有类的公共方法,如下面的方法所示。 ?使用反射获取类方法

private MethodInfo[] GetObjectMethods(string selectedObjClass) 
{ 
    MethodInfo[] methodInfos; 
    Assembly assembly = Assembly.GetAssembly(typeof(sampleAdapater)); 
    Type _type = assembly.GetType("SampleSolution.Data.MyData." + selectedObjClass); 

    ///get all the methods for the classname passed as string 

    return methodInfos; 

} 

请帮忙。 感谢

回答

42
MethodInfo[] methodInfos = Type.GetType(selectedObjcClass) 
          .GetMethods(BindingFlags.Public | BindingFlags.Instance); 
7
// get all public static methods of given type(public would suffer in your case, only to show how you could other BindingFlags) 
MethodInfo[] methodInfos = _type.GetMethods(BindingFlags.Public | BindingFlags.Static); 

Type.GetMethods Method (BindingFlags)