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

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

    With C# 8 onwards you can make it even more concise with the new switch. And with the use of discard option _ you can avoid creating innecesary variables when you don't need them, like this:

            return document switch {
                Invoice _ => "Is Invoice",
                ShippingList _ => "Is Shipping List",
                _ => "Unknown"
            };
    

    Invoice and ShippingList are classes and document is an object that can be either of them.

提交回复
热议问题