C#将动作转换为动作<bool>

Tom*_*tom 7 c#

我有一个具有以下属性的类:

public Action<bool> Action { get; private set; }
Run Code Online (Sandbox Code Playgroud)

我有一个构造函数Action<bool> 作为参数.

现在我想添加另一个接受类型对象的构造函数Action.我怎样才能转换ActionAction<bool>?在这种情况下,bool参数应该为true.

Dar*_*rov 13

public class Foo
{
    public Foo(Action<bool> action)
    {
        // Some existing constructor
    }

    public Foo(Action action): this(x => action())
    {
        // Your custom constructor taking an Action and 
        // calling the existing constructor
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过两种方式实例化此类,具体取决于您要调用的2个构造函数中的哪一个:

  1. var foo = new Foo(x => { Console.WriteLine("Hello"); }); (称第一个ctor)
  2. var foo = new Foo(() => { Console.WriteLine("Hello"); }); (打电话给第二个ctor)


Mar*_* Mp 6

Action a = () => aboolaction(true);
Run Code Online (Sandbox Code Playgroud)

  • 那就是将`Action <bool>`转换为`Action`.(他需要相反) (2认同)