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

后端 未结 30 2537
梦毁少年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 03:56

    You can use pattern matching in C# 7 or above:

    switch (foo.GetType())
    {
        case var type when type == typeof(Player):
            break;
        case var type when type == typeof(Address):
            break;
        case var type when type == typeof(Department):
            break;
        case var type when type == typeof(ContactType):
            break;
        default:
            break;
    }
    

提交回复
热议问题