在C#开发过程中,遇到在IWeb项目中,需要在一个类中调用其它类的某个方法(http请求的情况),因为想到了,之前了解过的反射,因此记录一下。
示例如下:
namespace IWeb.Test
{
public class AA
{
public string DoMethod(string postContent, HttpRequest _Request)
{
Object ErrorMsg = null;
Object strMsg1 = Utility.GetAndExecuteMethod("IWeb.Test.BB", "DoMethod", out ErrorMsg, new object[] { strJson, Request });
}
}
}
namespace IWeb.Test
{
public class BB
{
public string DoMethod(string postContent, HttpRequest _Request)
{
}
}
}
直接上代码:
public static object GetAndExecuteMethod(string className, string methodName, out object ErrorMsg, object[] parameters = null)
{
ErrorMsg = null;
try
{
var type = Type.GetType(className);
if (type == null)
throw new NullReferenceException("类" + className + "不存在");
var obj = type.Assembly.CreateInstance(className);
//调用其方法
var method = type.GetMethod(methodName);
if (method == null)
throw new NullReferenceException("方法" + methodName + "不存在");
//执行方法
return method.Invoke(obj, parameters);
}
catch (Exception ex)
{
ErrorMsg = ex.ToString();
return null;
}
}