2014-04-10 27 views
-2

我是C#的新手,我在調用Main()方法中的函數時遇到了一些問題。來自Main的調用函數()

class Program 
{ 
    static void Main(string[] args) 
    { 
     test(); 
    } 

    public void test() 
    { 
     MethodInfo mi = this.GetType().GetMethod("test2"); 
     mi.Invoke(this, null); 
    } 

    public void test2() 
    { 
     Console.WriteLine("Test2"); 
    } 
} 

我得到test();一個編譯器錯誤:是必需的非靜態字段

的對象引用。

我不太明白這些修飾符,所以我做錯了什麼?

我真正想做的是在Main()裏面有test()的代碼,但是當我這樣做的時候它給了我一個錯誤。

+0

隨着錯誤消息告訴你,你需要的對象引用調用非靜態成員。所以創建一個對象引用。 – Servy

+0

從方法?如何從一個方法中創建一個對象?或者你的意思是我必須把test()放到一個新類中? – Arbitur

+0

您需要定義該方法的類型實例來調用該類型的實例方法。我相信在obj-c中同樣如此。 – Servy

回答

1

只要把所有的邏輯到另一個類

class Class1 
    { 
     public void test() 
     { 
      MethodInfo mi = this.GetType().GetMethod("test2"); 
      mi.Invoke(this, null); 
     } 
     public void test2() 
     { 
      Console.Out.WriteLine("Test2"); 
     } 
    } 

static void Main(string[] args) 
     { 
      var class1 = new Class1(); 
      class1.test(); 
     } 
+1

這工作,C#是奇怪的:S – Arbitur

1

該方法必須是靜態的才能調用它。

+1

這就是我不能在靜態方法中使用MethodInfo的問題。 – Arbitur

+0

該方法不是靜態的。 –

+1

@Arbitur靜態方法的類型在編譯時總是已知的;沒有必要動態獲取它。 – Servy

2

如果你還是希望有test()爲實例方法:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Program p = new Program(); 
     p.test(); 
    } 

    void Test() 
    { 
     // I'm NOT static 
     // I belong to an instance of the 'Program' class 
     // You must have an instance to call me 
    } 
} 

或者更確切地說,使其靜態:

class Program 
{ 
    static void Main(string[] args) 
    { 
     Test(); 
    } 

    static void Test() 
    { 
     // I'm static 
     // You can call me from another static method 
    } 
} 

獲取靜態方法的信息:

typeof(Program).GetMethod("Test", BindingFlags.Static); 
+0

+1爲理解的修飾符解釋:) – Arbitur