反射调用DLL

时间:2024-09-04 15:35:50

public static type GetClassType(string ClassName,string dllname)

{

Type ClassType =null;

foreach(Assembly am in AppDomain.CurrentDomain.GetAssemblies())

{

if (am.FullName.Contains(dllname))

{

ClassType=am.GetType(ClassName);

if (ClassType !=null) break;

}
}

if (ClassType==null)

{

string filename=string.Empty;

if (dllname.EndsWith(".dll"))

{

filename=Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dllname);

}

else

filename=string.Format("{0}.dll ",AppDomain.CurrentDomain.BaseDirectory, dllname));

Assembly asm=Assembly.LoadFile(filename);

ClassType =asm.GetType(ClassName);

}

return ClassType;

}

private static Dictionary <int,object> ServiceDe=new Dictionary<int,object>();

delegate Result ActionDelegate<T>(T Data);

private static Result ReflectionMethod<T>(FormShowRequest request)

{

object doAction =null;

string dllname =request.module;

string classname=request.action;

string method=request.method;

param sdata=request.param;

Result result=new Result();

string strKey=dllname+“,”+classname+","+method;

int hashCode=strKey.GetHashCode();

if (!ServiceDelegates.ContainsKey(hashCode))

{

Type clsname =GetClassType(classname,dllname);

object action=clsname.GetConstructor(Type.EmptyTypes).Invoke(null);

doAction =Delegate.CreateDelegate(typeof(ActionDelegate<T>),action,method);

if (ServiceDelegates!=null && doAction!=null)

ServiceDelegates.Add(hashCode,doAction);

}

else

{

doAction=ServiceDelegates[hashCode];

}

if (doAction!=null)

{

result =((ActionDelegate<param>)doAction)(sdata);

return result;

}

else

{

result=new Result();

result.errors=“反射调用错误!”

}
}