簡體   English   中英

關於使用反射調用方法的問題

[英]Question on calling a method using reflection

今天美麗的晴天! 但是,我不能享受它,因為我已經嘗試在Mono中調用動態方法2天了:-(

故事:

我正在嘗試在名為“模板”的類中調用它。 基本上,如果我可以將字符串傳遞給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);

如果您需要更多信息,請告訴我。

提前致謝!!

你不需要模板的另一個實例,如果你要調用的方法是在同一class.You可以使用

    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!");
        }
   }

我用以下方法進行了測試:

class Program
{
    public static void Main(string[] args)
    {
        Template m = new Template("methodIWantToCall");
        Console.ReadKey(true);

    }
 }

Activator.CreateInstance的第一個參數是類的類型,然后跟隨該類型的構造函數的參數。

您正在嘗試不使用構造函數的參數來創建Template類的實例。 但是沒有沒有參數的構造函數。

嘗試將構造函數添加到您的Template類中,該構造函數不使用任何參數:

public class Template
{
    //......
    public Template()
    {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM