use*_*737 2 .net c# generics delegates optional-parameters
我有一个目前看起来像这样的课程:
public Action<string> Callback { get; set; }
public void function(string, Action<string> callback =null)
{
if (callback != null) this.Callback = callback;
//do something
}
Run Code Online (Sandbox Code Playgroud)
现在我想要的是采用一个可选参数,如:
public Action<optional, string> Callback { get; set; }
Run Code Online (Sandbox Code Playgroud)
我试过:
public Action<int optional = 0, string> Callback { get; set; }
Run Code Online (Sandbox Code Playgroud)
这是行不通的。
有没有办法允许Action<...>
采用一个可选参数?
你不能用 a 来做到这一点System.Action<T1, T2>
,但你可以像这样定义你自己的委托类型:
delegate void CustomAction(string str, int optional = 0);
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
CustomAction action = (x, y) => Console.WriteLine(x, y);
action("optional = {0}"); // optional = 0
action("optional = {0}", 1); // optional = 1
Run Code Online (Sandbox Code Playgroud)
不过,请注意关于此的一些事情。
您可以使这个委托通用,但很可能,您只能使用default(T2)
默认值,如下所示:
delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);
Run Code Online (Sandbox Code Playgroud)