2

I have a class that currently looks like this:

public Action<string> Callback { get; set; }

public void function(string, Action<string> callback =null)
{
   if (callback != null) this.Callback = callback;
   //do something
}

Now what I want is to take an optional parameter like:

public Action<optional, string> Callback { get; set; }

I tried:

public Action<int optional = 0, string> Callback { get; set; }

it does not work.

Is there any way to allow Action<...> take one optional parameter?

4

1 回答 1

10

你不能用 a 来做到这一点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

不过,请注意一些关于此的事情。

  1. 就像在普通方法中一样,必填参数不能在可选参数之后,所以我不得不在这里颠倒参数的顺序。
  2. 默认值是在您定义委托时指定的,而不是在您声明变量实例的地方。
  3. 您可以将此委托设为通用,但最有可能的是,您只能使用default(T2)默认值,如下所示:

    delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
    CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);
    
于 2013-10-25T18:54:23.103 回答