Encapsulating Action and Func?

前端 未结 4 1441
栀梦
栀梦 2021-02-08 09:46

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:56

    The following interfaces should do the trick -- it's essentially copying the Nullable pattern

    public interface IActionBase
    {
           bool HasResult { get; }
           void Execute() { }
           object Result { get; }
    }
    
    public interface IActionBase : IActionBase
    {
           new T Result { get; }
    }
    
    public sealed class ActionWithReturnValue : IActionBase
    {
           public ActionWithReturnValue(Func action) {  _action = action; }
           private Func _action;
    
           public bool HasResult { get; private set; }
           object IActionBase.Result { get { return this.Result; } }
           public T Result { get; private set; }
           public void Execute()
           {
                HasResult = false;
                Result = default(T);
                try 
                { 
                     Result = _action();
                     HasResult = true;
                 }
                catch
                {
                    HasResult = false;
                    Result = default(T);   
                }  
           }
    
    }
    
    public sealed class ActionWithoutReturnValue : IActionBase
    {
          public bool HasResult { get { return false; } }
          object IActionBase.Result { get { return null; } }
          public void Execute() { //... }
    }
    

提交回复
热议问题