2015-04-22 78 views
3

在C++中,我能夠創建我的方法指針而不知道它將被調用哪個實例,但在C#中我無法做到 - 我需要創建委託實例。像C++中的C#方法指針

這就是我在尋找:

這裏是MSDN

using System; 
using System.Windows.Forms; 

public class Name 
{ 
    private string instanceName; 

    public Name(string name) 
    { 
     this.instanceName = name; 
    } 

    public void DisplayToConsole() 
    { 
     Console.WriteLine(this.instanceName); 
    } 

    public void DisplayToWindow() 
    { 
     MessageBox.Show(this.instanceName); 
    } 
} 

public class testTestDelegate 
{ 
    public static void Main() 
    { 
     Name testName = new Name("Koani"); 
     Action showMethod = testName.DisplayToWindow; 
     showMethod(); 
    } 
} 

代碼,但我想這樣做:

public class testTestDelegate 
{ 
    public static void Main() 
    { 
     Name testName = new Name("Koani"); 
     Action showMethod = Name.DisplayToWindow; 
     testName.showMethod(); 
    } 
} 
+0

似乎被稱爲[打開實例委託](http://stackoverflow.com/questions/4188592/passing-around-member-functions-in-c-sharp)。 – chris

+0

如果你想'testName.showMethod();'語法,我相信答案是否定的。 –

回答

2

您可以創建一個委託,它以您的實例作爲參數:

Name testName = new Name("Koani"); 
Action<Name> showMethod = name => name.DisplayToWindow(); 
showMethod(testName); 
+0

哦,太棒了,可以填寫我所需要的! –