简体   繁体   中英

Question on calling a method using reflection

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!!

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);

    }
 }

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()
    {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM