C# 反射笔记
一、获取该类(BaseMatchRule)的所有派生类
var t = typeof(BaseMatchRule); var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(item => item.GetTypes()).Where(a => a.BaseType != null && a.BaseType.Name == t.Name).ToList();
遍历 types 中每个 Item 的Name就是派生类的名称
二、通过类名称(ClassName)实例化该类
Assembly assembly = Assembly.GetExecutingAssembly(); object matchRule = assembly.CreateInstance($"FirstPropertiesBackendAPI.NewPropertyMatchRules.{ClassName}");
"FirstPropertiesBackendAPI.NewPropertyMatchRules.{item.Name}"为命名空间
再获该类的所有方法
MethodInfo[] methodInfo = matchRule.GetType().GetMethods();
遍历 methodInfo中的每个item的Name就是该方法的名称
三、通过类名(ClassName)和方法名(MethodName)调用该方法
var str = "参数1";
var str2 = "参数2";
Assembly assembly = Assembly.GetExecutingAssembly(); object matchRule = assembly.CreateInstance($"FirstPropertiesBackendAPI.NewPropertyMatchRules.{ClassName}"); MethodInfo methodInfo = matchRule.GetType().GetMethod($"{MethodName}"); SKMCResult res = (SKMCResult)methodInfo.Invoke(matchRule, new object[] {str,str2});
SKMCResult为返回的结果