我有一个目前看起来像这样的课程:
public Action<string> Callback { get; set; }
public void function(string, Action<string> callback =null)
{
if (callback != null) this.Callback = callback;
//do something
}
现在我想要的是采用可选参数,如:
public Action<optional, string> Callback { get; set; }
我试过了:
public Action<int optional = 0, string> Callback { get; set; }
它不起作用。
有没有办法让Action<...>
获取一个可选参数?
答案 0 :(得分:3)
您无法使用System.Action<T1, T2>
执行此操作,但您可以像这样定义自己的委托类型:
delegate void CustomAction(string str, int optional = 0);
然后像这样使用它:
CustomAction action = (x, y) => Console.WriteLine(x, y);
action("optional = {0}"); // optional = 0
action("optional = {0}", 1); // optional = 1
请注意一些关于此的事情。
您可以将此委托设为通用,但最有可能的是,您只能使用default(T2)
作为默认值,如下所示:
delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);