函數如下,有注釋,請自行查看:)
注:
1、ReturnMessage 是我自寫的一個類,作用請查看我的其他文章,我也把這個類一並附在後面
2、通過NameSpaceAndClassName和MethodName實際上就可以精確定位一個方法了如調用abc.dll裡的namespace1.Class1.Main,調用起來就是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);//調入文件(不限於dll,exe亦可,只要是.Net)
Type TP=Ass.GetType(NameSpaceAndClassName);//NameSpaceAndClassName是"名字空間.類名",如"namespace1.Class1"
MethodInfo MI=TP.GetMethod(MethodName);//MethodName是要調用的方法名,如"Main"
object MeObj=System.Activator.CreateInstance(TP);
MI.Invoke(MeObj,Parameters);//Parameters是調用目標方法時傳入的參數列表
return new ReturnMessage(true,"成功調用",1);
}
catch(Exception e)
{
return new ReturnMessage(false,"出現異常,消息為:"+e.Message,-1,e);
}
}
附ReturnMessage
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)
&
nbsp; {
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.htm