Use reflection to call methods in any .net library
Author:Eve Cole
Update Time:2009-07-01 15:48:58
The function is as follows, with comments, please check it yourself :)
Note:
1. ReturnMessage is a class I wrote myself. Please check my other articles for its function. I also attached this class at the back.
2. Through NameSpaceAndClassName and MethodName, you can actually accurately locate a method. For example, when calling namespace1.Class1.Main in abc.dll, the call is CallAssembly("abc.dll","namespace1.Class1","Main",null )
public static ReturnMessage CallAssembly(string Path,string NameSpaceAndClassName,string MethodName,object[] Parameters)
{
try
{
Assembly Ass=Assembly.LoadFrom(Path);//Load the file (not limited to dll, exe can also be used, as long as it is .net)
Type TP=Ass.GetType(NameSpaceAndClassName);//NameSpaceAndClassName is "namespace.classname", such as "namespace1.Class1"
MethodInfo MI=TP.GetMethod(MethodName);//MethodName is the method name to be called, such as "Main"
object MeObj=System.Activator.CreateInstance(TP);
MI.Invoke(MeObj,Parameters);//Parameters is the parameter list passed in when calling the target method
return new ReturnMessage(true,"successfully called",1);
}
catch(Exception e)
{
return new ReturnMessage(false,"An exception occurred, the message is: "+e.Message,-1,e);
}
}
AttachedReturnMessage
public class ReturnMessage
{
public ReturnMessage()
{
this.m_Succeed=false;
this.m_Message="";
this.m_Code=-1000;
this.m_Data=null;
}
public ReturnMessage(bool IsSucceed)
{
this.m_Succeed=IsSucceed;
}
public ReturnMessage(bool IsSucceed,string Message)
{
this.m_Succeed=IsSucceed;
this.m_Message=Message;
}
public ReturnMessage(bool IsSucceed,string Message,int Code)
{
this.m_Succeed=IsSucceed;
this.m_Message=Message;
this.m_Code=Code;
}
public ReturnMessage(bool IsSucceed,string Message,int Code,object Data)
{
this.m_Succeed=IsSucceed;
this.m_Message=Message;
this.m_Code=Code;
this.m_Data=Data;
}
public ReturnMessage(bool IsSucceed,string Message,int Code,object Data,object[] Datas)
{
this.m_Succeed=IsSucceed;
this.m_Message=Message;
this.m_Code=Code;
this.m_Data=Data;
this.m_Datas=Datas;
}
//
bool m_Succeed;
string m_Message;
int m_Code;
object m_Data;
object[] m_Datas;
public bool Succeed
{
get{return m_Succeed;}
set{m_Succeed=value;}
}
public string Message
{
get{return m_Message;}
set{m_Message=value;}
}
public int Code
{
get{return m_Code;}
set{m_Code=value;}
}
public object Data
{
get{return m_Data;}
set{m_Data=value;}
}
public object[] Datas
{
get{return m_Datas;}
set{m_Datas=value;}
}
}
http://www.cnblogs.com/niit007/archive/2006/08/13/475574.html