C#方法指针就像在C ++中一样

时间:2015-04-22 15:53:30

标签: c# c++ delegates

在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();
    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个以实例作为参数的委托:

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