【问题标题】:C# referencing methods through variables?C#通过变量引用方法?
【发布时间】:2012-03-28 11:12:21
【问题描述】:
假设我有一个方法
public static void Blah(object MyMethod) { // i dont know what to replace object with
MyMethod; // or however you would use the variable
}
所以基本上我需要能够通过变量引用方法
【问题讨论】:
标签:
c#
visual-studio
winapi
variables
methods
【解决方案1】:
您正在寻找a delegate。
public delegate void SomeMethodDelegate();
public void DoSomething()
{
// Do something special
}
public void UseDoSomething(SomeMethodDelegate d)
{
d();
}
用法:
UseDoSomething(DoSomething);
或者使用 lambda 语法(如果 DoSomething 是 Hello World):
UseDoSomething(() => Console.WriteLine("Hello World"));
还有Action 和Func 类型的代表可用的快捷语法:
public void UseDoSomething(Action d)
如果您需要从您的委托中返回一个值(例如我的示例中的 int),您可以使用:
public void UseDoSomething2(Func<int> d)
注意:Action 和 Func 提供允许传递参数的通用重载。
【解决方案2】:
.Net 框架内置了一堆委托类型,使这更容易。因此,如果 MyMethod 采用 string 参数,您可以这样做:
public static void Blah(Action<string> MyMethod) {
MyMethod;
}
如果它需要两个 ints 并返回一个 long 你会这样做:
public static void Blah(Func<int, int, long> MyMethod) {
MyMethod;
}
Action<> 和 Func<> 有不同的版本,您可以根据需要指定不同数量的类型参数。