如何为Action [复制]获取可选参数

时间:2022-10-31 10:51:18

This question already has an answer here:

这个问题在这里已有答案:

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?

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

1 个解决方案

#1


3  

You can't do this with a System.Action<T1, T2>, but you could define your own delegate type like this:

您不能使用System.Action 执行此操作,但您可以像这样定义自己的委托类型: ,t2>

delegate void CustomAction(string str, int optional = 0);

And then use it like this:

然后像这样使用它:

CustomAction action = (x, y) => Console.WriteLine(x, y);
action("optional = {0}");    // optional = 0
action("optional = {0}", 1); // optional = 1

Notice a few things about this, though.

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

  1. Just like in normal methods, a required parameter cannot come after an optional parameter, so I had to reverse the order of the parameters here.
  2. 就像在普通方法中一样,必需参数不能在可选参数之后出现,所以我不得不在这里颠倒参数的顺序。
  3. The default value is specified when you define the delegate, not where you declare an instance of the variable.
  4. 定义委托时指定默认值,而不是声明变量实例的位置。
  5. You could make this delegate generic, but most likely, you'd only be able to use default(T2) for the default value, like this:

    您可以将此委托设为通用,但最有可能的是,您只能使用默认值(T2)作为默认值,如下所示:

    delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
    CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);
    

#1


3  

You can't do this with a System.Action<T1, T2>, but you could define your own delegate type like this:

您不能使用System.Action 执行此操作,但您可以像这样定义自己的委托类型: ,t2>

delegate void CustomAction(string str, int optional = 0);

And then use it like this:

然后像这样使用它:

CustomAction action = (x, y) => Console.WriteLine(x, y);
action("optional = {0}");    // optional = 0
action("optional = {0}", 1); // optional = 1

Notice a few things about this, though.

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

  1. Just like in normal methods, a required parameter cannot come after an optional parameter, so I had to reverse the order of the parameters here.
  2. 就像在普通方法中一样,必需参数不能在可选参数之后出现,所以我不得不在这里颠倒参数的顺序。
  3. The default value is specified when you define the delegate, not where you declare an instance of the variable.
  4. 定义委托时指定默认值,而不是声明变量实例的位置。
  5. You could make this delegate generic, but most likely, you'd only be able to use default(T2) for the default value, like this:

    您可以将此委托设为通用,但最有可能的是,您只能使用默认值(T2)作为默认值,如下所示:

    delegate void CustomAction<T1, T2>(T1 str, T2 optional = default(T2));
    CustomAction<string, int> action = (x, y) => Console.WriteLine(x, y);