问题描述
我有一个使用插件架构的主项目。主项目无法了解插件。为此,我使用 https://web.archive.org/web/20170506195518/http://www.squarewidget.com:80/pluggable-architecture-in-asp.net-mvc-4
虽然我不完全明白这是做什么的,但它对我有用。
我现在需要做的是在不相关的 DLL 中调用一个方法。我有一个示例方法...
namespace MyPlugins.Controllers
{
public class Calculate
{
public float Add(float a,float b)
{
return a + b;
}
}
}
string MethodToCall = "MyPlugins.Controllers.Calculate.Add";
float a = 12.7F;
float ab = 123F;
dynamic result = CallMethod(MethodToCall,new object[] { a,ab });
为此,我查看并尝试了各种方法,但没有一种对我有用。这是我当前的 CallMethod。
public dynamic CallMethod(string Method,object[] Params = null)
{
string[] Methodpath = Method.Split('.');
try
{
string MethodType = Methodpath[0];
if (Methodpath.Length > 2)
{
for (int i = 1; i < Methodpath.Length - 1; i++)
{
MethodType += "." + Methodpath[i];
}
}
Type t = Type.GetType(MethodType);
Type[] myObjects = new Type[Params.Count()];
for (int i = 0; i < Params.Length; i++)
{
myObjects[i] = Type.GetType(Params[i].GetType().FullName);
}
var methodInfo = t.getmethod(Methodpath[Methodpath.Length - 1],myObjects);
if (methodInfo == null)
{
// never throw generic Exception - replace this with some other exception type
throw new Exception("No such method exists.");
}
var o = Activator.CreateInstance(t);
object[] parameters = new object[Params.Length];
for (int i = 0; i < Params.Length; i++)
{
parameters[i] = Params[i];
}
var r = methodInfo.Invoke(o,parameters);
return r;
}
catch
{
return null;
}
}
我看到的问题是 Type.GetType(MethodType) 总是返回 null。
我的想法是,当我使用 SquareWidget 示例(上面的链接)时,程序集已加载,因此应该能够调用它。
感谢您的帮助。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)