通过反射动态调用方法
简介
System.Reflection 命名空间包含通过检查托管代码中程序集、模块、成员、参数和其他实体的元数据来检索其相关信息的类型。 这些类型还可用于操作加载类型的实例,例如挂钩事件或调用方法。
↑上边是微软 MSDN 的介绍,balabala一大堆…,总之反射调用它就对了,通过类库类名以及方法名称调用方法。
使用
通过反射运行方法
调用方法代码
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | 
 
 
 
 
 
 
 public static object RunMethod(string strLibraryName, string strClassName, string strMethodName, object[] parameters)
 {
 try
 {
 Type type = Type.GetType($"{strLibraryName}.{strClassName}");
 if (type != null)
 {
 var vMethod = type.GetMethod(strMethodName);
 if (vMethod != null)
 {
 return vMethod.Invoke(Activator.CreateInstance(type), parameters);
 }
 }
 return null;
 }
 catch (Exception)
 {
 return null;
 }
 }
 
 | 
调用方法示例
| 12
 
 | var parameters = new object[] { item };RunMethod("ReflectionProject_Test", "ClassName", "MethodName", parameters);
 
 | 
通过反射接口插件式开发
定义接口
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | 
 
 public interface MenuPluginInterface
 {
 
 
 
 void Click();
 
 
 
 
 string strFunctionName { get; }
 
 
 
 
 string strFunctionGroup { get; }
 }
 
 | 
插件继承接口
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 
 | 
 
 public class TestCommand : MenuPluginInterface
 {
 
 
 
 public void Click()
 {
 
 }
 
 
 
 
 public string strFunctionName
 {
 get { return "测试功能"; }
 }
 
 
 
 
 public string strFunctionGroup
 {
 get { return "测试分组"; }
 }
 }
 
 | 
反射方法
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | 
 
 
 
 
 public static bool RunPluginClick(string strDllPath, string strClassName)
 {
 try
 {
 
 Assembly assembly = Assembly.LoadFrom(strDllPath);
 Type type = assembly.GetType(strClassName);
 if (type != null)
 {
 var container = new UnityContainer();
 container.RegisterType<MenuPluginInterface>(new ContainerControlledLifetimeManager());
 container.RegisterType(typeof(MenuPluginInterface), type);
 var manager = container.Resolve<MenuPluginInterface>();
 manager.Click();
 return true;
 }
 else
 {
 return false;
 }
 }
 catch (Exception)
 {
 return false;
 }
 }
 
 | 
通过反射打开插件
| 12
 
 | string strProjectDll = "ReflectionProject_Test.dll";RunPluginClick(strProjectDll, "ReflectionProject_Test.TestCommand");
 
 |