如何为Action <t1,t2> </t1,t2>获取可选参数

时间:2013-10-25 18:45:18

标签: c# .net 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
}

现在我想要的是采用可选参数,如:

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

我试过了:

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

它不起作用。

有没有办法让Action<...>获取一个可选参数?

1 个答案:

答案 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

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

  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);