使用反射获取类方法

时间:2011-03-29 15:42:43

标签: c# reflection

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

 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;

 }

请帮忙。 感谢

3 个答案:

答案 0 :(得分:48)

MethodInfo[] methodInfos = Type.GetType(selectedObjcClass) 
                           .GetMethods(BindingFlags.Public | BindingFlags.Instance);

答案 1 :(得分: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)

答案 2 :(得分:2)