假设我有一个函数。我希望在一个变量中添加对这个函数的引用。
这样,我就可以从变量'bar'调用函数'foo(bool foobar)',就像调用函数一样。例如:'bar(foobar)'。
怎么做呢?
看起来你想将一个Func
保存到变量中以备后用。可以参考这里的例子:
using System;
public class GenericFunc
{
public static void Main()
{
// Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod = UppercaseString;
string name = "Dakota";
// Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
}
private static string UppercaseString(string inputString)
{
return inputString.ToUpper();
}
}
看看方法UppercaseString
如何保存到一个名为convertMethod
的变量中,然后稍后可以调用它:convertMethod(name)
。
void Foo(bool foobar)
{
/* method implementation */
}
使用 Action
委托
Public Action<bool> Bar;
Bar = Foo;
调用该函数;
bool foobar = true;
Bar(foobar);
你需要知道函数的签名,并创建一个委托。
有现成的委托用于返回值的函数和用于没有返回类型的函数。前面两个链接都指向通用类型,可以接受多达15个类型参数(因此可用于最多使用那么多参数的函数)。
如果您打算在大于本地范围的范围内使用对函数的引用,则可以考虑定义自己的自定义委托。但是大多数情况下,Action
和Func
非常好用。
更新:
请查看这个问题,了解在定义自己的委托或不定义之间的选择。