C#将Action转换为Action<bool>

7
我有一个类,它有以下属性:
public Action<bool> Action { get; private set; }

我有一个构造函数,它以 Action<bool> 为参数。

现在,我想添加另一个构造函数,接受类型为 Action 的对象。如何将 Action 转换为 Action<bool>?在这种情况下,bool 参数应该为 true。

2个回答

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
    }
}

根据需要调用的两个构造函数,您可以以两种方式实例化此类:

  1. var foo = new Foo(x => { Console.WriteLine("Hello"); });(调用第一个构造函数)
  2. var foo = new Foo(() => { Console.WriteLine("Hello"); });(调用第二个构造函数)

6
Action a = () => aboolaction(true);

2
那就是将一个 Action<bool> 转换为一个 Action。(他需要相反的) - Servy
你说得对,我把问题理解反了(原始问题不够清晰,现在的问题更明确)。 - Marco Mp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接