在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 :(得分:2)
您可以创建一个以实例作为参数的委托:
Name testName = new Name("Koani");
Action<Name> showMethod = name => name.DisplayToWindow();
showMethod(testName);