Advertisement
GeneralGDA

Expected of T

Jun 27th, 2019
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1.     public static class Code
  2.     {
  3.         // Не метод Expected<T>, что б не писать generic тип для него (типа).
  4.         [Pure]
  5.         public static Expected<T> Expect<T>(Func<T> produce)
  6.         {
  7.             try
  8.             {
  9.                 return new Expected<T>(produce());
  10.             }
  11.             catch (Exception e)
  12.             {
  13.                 return new Expected<T>(e);
  14.             }
  15.         }
  16.     }
  17.  
  18.     [PublicAPI]
  19.     public struct Expected<T>
  20.     {
  21.         private readonly T _value;
  22.         private readonly Exception _failure;
  23.  
  24.         public Expected(T value)
  25.         {
  26.             _value = value;
  27.             _failure = null;
  28.         }
  29.  
  30.         public Expected([NotNull] Exception failure)
  31.         {
  32.             ThrowIf.Argument.IsNull(failure, nameof(failure));
  33.  
  34.             _failure = failure;
  35.             _value = default(T);
  36.         }
  37.  
  38.         // Синоним для Value на случай если по месту вызова более выразительно выглядит Get().
  39.         [Pure]
  40.         public T Get()
  41.         {
  42.             if (null != _failure)
  43.             {
  44.                 throw new AggregateException(_failure);
  45.             }
  46.  
  47.             return _value;
  48.         }
  49.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement