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

后端 未结 30 3029
梦毁少年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:11

    Yes, thanks to C# 7 that can be achieved. Here's how it's done (using expression pattern):

    switch (o)
    {
        case A a:
            a.Hop();
            break;
        case B b:
            b.Skip();
            break;
        case C _: 
            return new ArgumentException("Type C will be supported in the next version");
        default:
            return new ArgumentException("Unexpected type: " + o.GetType());
    }
    

提交回复
热议问题