关于使用反射调用方法的问题
今天阳光明媚的一天!然而,我不能享受它,因为我已经尝试在 Mono 中调用动态方法 2 天了:-(
故事:
我试图在一个名为“Template”的类中调用它。基本上我会喜欢它如果我可以将一个字符串传递给 Template 并让它运行该方法,该方法是在 Template 类中定义的。到目前为止,模板类看起来像这样。
namespace Mash
{
public class Template
{
public Template(string methodToCall)
{
Type type = this.GetType();
object ob = Activator.CreateInstance(type);
object[] arguments = new object[52];
type.InvokeMember(methodToCall,
BindingFlags.InvokeMethod,
null,
ob,
arguments);
}
public void methodIWantToCall()
{
Console.WriteLine("I'm running the Method!");
}
}
}
但是,一旦我运行它,我就会得到。
“未处理的异常:System.MissingMethodException:未找到方法:“未找到默认构造函数...Mash.Template 的ctor()”。
我认为这里失败了:
object ob = Activator.CreateInstance(type);
如果您需要更多信息,请告诉我。
提前致谢!!
Beautiful sunny day today! However, I can't enjoy it because I've been trying to call a dynamic method in Mono for 2 days :-(
The Story:
I'm trying to call it within a class called 'Template'. Basically I would love it if I could pass a string to Template and have it run that method, which is defined within the Template class. The template class looks like this so far..
namespace Mash
{
public class Template
{
public Template(string methodToCall)
{
Type type = this.GetType();
object ob = Activator.CreateInstance(type);
object[] arguments = new object[52];
type.InvokeMember(methodToCall,
BindingFlags.InvokeMethod,
null,
ob,
arguments);
}
public void methodIWantToCall()
{
Console.WriteLine("I'm running the Method!");
}
}
}
No errors are received during compile time. Once I run it, however, I get
'Unhandled Exception: System.MissingMethodException: Method not found: 'Default constructor not found...ctor() of Mash.Template'.'
I think it is failing here:
object ob = Activator.CreateInstance(type);
If you need any more information please let me know.
Thanks in advance!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要调用的方法位于同一个类中,则不需要 Template 的另一个实例。您可以使用
我测试过的this:
you don't need another instance of Template if the method you want to call is in the same class.You can use this
I tested it with:
Activator.CreateInstance 的第一个参数是类的类型,然后是该类型的构造函数的参数。
您尝试使用不带参数的构造函数来创建
Template
类的实例。但不存在没有参数的构造函数。尝试在您的
Template
类中添加一个不带参数的构造函数:The first argument of
Activator.CreateInstance
is the type of the class, and then follows the argument of the constructor of the type.You're trying to create an instance of the
Template
class using no parameter for the constructor. But there isn't a constructor with no parameter.Try adding a constructor into your
Template
class, which takes no parameters: