Is there a better alternative than this to 'switch on type'?

后端 未结 30 2513
梦毁少年i
梦毁少年i 2020-11-22 03:28

Seeing as C# can\'t switch on a Type (which I gather wasn\'t added as a special case because is relationships mean that more than one distinct

30条回答
  •  清酒与你
    2020-11-22 04:10

    This is an alternate answer that mixes contributions from JaredPar and VirtLink answers, with the following constraints:

    • The switch construction behaves as a function, and receives functions as parameters to cases.
    • Ensures that it is properly built, and there always exists a default function.
    • It returns after first match (true for JaredPar answer, not true for VirtLink one).

    Usage:

     var result = 
       TSwitch
         .On(val)
         .Case((string x) => "is a string")
         .Case((long x) => "is a long")
         .Default(_ => "what is it?");
    

    Code:

    public class TSwitch
    {
        class CaseInfo
        {
            public Type Target { get; set; }
            public Func Func { get; set; }
        }
    
        private object _source;
        private List> _cases;
    
        public static TSwitch On(object source)
        {
            return new TSwitch { 
                _source = source,
                _cases = new List>()
            };
        }
    
        public TResult Default(Func defaultFunc)
        {
            var srcType = _source.GetType();
           foreach (var entry in _cases)
                if (entry.Target.IsAssignableFrom(srcType))
                    return entry.Func(_source);
    
            return defaultFunc(_source);
        }
    
        public TSwitch Case(Func func)
        {
            _cases.Add(new CaseInfo
            {
                Func = x => func((TSource)x),
                Target = typeof(TSource)
            });
            return this;
        }
    }
    

提交回复
热议问题