用反射调用任意.net库中的方法
作者:Eve Cole
更新时间:2009-07-01 15:48:58
函数如下,有注释,请自行查看:)
注:
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)
{
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