2011-03-29 84 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)