且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

封装动作< T>和Func< T> ;?

更新时间:2022-04-02 21:01:39

如果您想要一个轻量级的解决方案,那么最简单的选择就是编写两个具体的类.一个将包含类型为Action的属性,另一个将包含类型为Func<T>的属性:

If you want a lightweight solution, then the easiest option would be to write two concrete classes. One will contain a property of type Action and the other a property of type Func<T>:

public class ActionWithResult<T> : ActionBase { 
  public Func<T> Action { get; set; } 
}

public class ActionWithoutResult : ActionBase {
  public Action Action { get; set; }
}

然后,您可以像这样构造两种类型:

Then you can construct the two types like this:

var a1 = new ActionWithResult<int> { 
  CanExecute = true,
  Action = () => { 
    Console.WriteLine("hello!");
    return 10; 
  }
}

如果您不想使Action属性为读/写,则可以将操作委托作为参数传递给构造函数,并使该属性为只读.

If you don't want to make Action property read/write, then you could pass the action delegate as an argument to the constructor and make the property readonly.

C#需要两个不同的代表来表示函数和动作的事实非常令人讨厌.人们使用的一种解决方法是定义一个表示无返回值"的类型Unit,并使用它代替void.然后,您的类型将仅为Func<T>,并且可以使用Func<Unit>而不是Action. Unit类型可能如下所示:

The fact that C# needs two different delegates to represent functions and actions is quite annoying. One workaround that people use is to define a type Unit that represents "no return value" and use it instead of void. Then your type would be just Func<T> and you could use Func<Unit> instead of Action. The Unit type could look like this:

public class Unit {
  public static Unit Value { get { return null; } }
}

要创建Func<Unit>值,请输入:

Func<Unit> f = () => { /* ... */ return Unit.Value; }