【问题标题】:How to take an optional parameter for Action<T1,T2> [duplicate]如何为 Action<T1,T2> 采用可选参数 [重复]
【发布时间】:2013-10-25 18:45:17
【问题描述】:

我有一个目前看起来像这样的课程:

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&lt;...&gt; 带一个可选参数?

【问题讨论】:

标签: c# .net generics delegates optional-parameters


【解决方案1】:

您不能使用 System.Action&lt;T1, T2&gt; 来执行此操作,但您可以像这样定义自己的委托类型:

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

【讨论】:

  • 通用方法有一个限制,即您始终必须为可选参数提供类型,即使您不需要它。为了使其真正成为可选,您必须为每个用例声明多个委托,例如:delegate void CustomAction&lt;T1&gt;(T1 first);delegate void CustomAction&lt;T1, T2&gt;(T1 first, T2 second);在微软做。
猜你喜欢
  • 2011-12-03
  • 1970-01-01
  • 2015-11-06
  • 2012-09-09
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多