asp.net动态加载程序集创建指定类的实例及调用指定方法
以下类中有三个方法:
LoadAssembly:加载指定路径的程序集
GetInstance:根据Type动态获取实例,用泛型接到返回的类型
ExecuteMothod:执行实例中的指定方法
/// <summary> /// 继承自MarshalByRefObject表示允许跨域通信 /// </summary> public class RemoteLoader : MarshalByRefObject { private Assembly _assembly; public void LoadAssembly(string assemblyFile) { try { _assembly = Assembly.LoadFrom(assemblyFile); //return _assembly; } catch (Exception ex) { throw ex; } } public T GetInstance<T>(string typeName) where T : class { if (_assembly == null) return null; var type = _assembly.GetType(typeName); if (type == null) return null; return Activator.CreateInstance(type) as T; } public void ExecuteMothod(string typeName, string methodName) { if (_assembly == null) return; var type = _assembly.GetType(typeName); var obj = Activator.CreateInstance(type); Expression<Action> lambda = Expression.Lambda<Action>(Expression.Call(Expression.Constant(obj), type.GetMethod(methodName)), null); lambda.Compile()(); } }