Encapsulating Action and Func?

前端 未结 4 1996
轮回少年
轮回少年 2021-02-08 09:42

I\'m trying to make a design for some sort of IExecutable interface. I will not get into details, but the point is that I have several Actions that need to be executed from a ba

4条回答
  •  别那么骄傲
    2021-02-08 09:57

    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:

    public class ActionWithResult : ActionBase { 
      public Func 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 { 
      CanExecute = true,
      Action = () => { 
        Console.WriteLine("hello!");
        return 10; 
      }
    }
    

    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.

    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 and you could use Func instead of Action. The Unit type could look like this:

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

    To create a Func value, you'll write:

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

提交回复
热议问题