Reputation: 351
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!!
Upvotes: 0
Views: 1571
Reputation: 25864
you don't need another instance of Template if the method you want to call is in the same class.You can use this
public class Template
{
public Template(string methodToCall)
{
this.GetType().InvokeMember(methodToCall,
BindingFlags.InvokeMethod,
null,
this,
null);
}
public void methodIWantToCall()
{
Console.WriteLine("I'm running the Method!");
}
}
I tested it with:
class Program
{
public static void Main(string[] args)
{
Template m = new Template("methodIWantToCall");
Console.ReadKey(true);
}
}
Upvotes: 2
Reputation: 5364
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:
public class Template
{
//......
public Template()
{
}
}
Upvotes: 1