【问题标题】:C# method pointer like in C++ [duplicate]类似于 C++ 中的 C# 方法指针 [重复]
【发布时间】:2015-04-22 15:53:30
【问题描述】:

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

【问题讨论】:

  • 好像被称为open instance delegate
  • 如果你想要testName.showMethod();语法那我相信答案是否定的。

标签: c# c++ delegates


【解决方案1】:

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

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

【讨论】:

  • 哦,太好了,可以完全满足我的需要!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多