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

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

    Yes - just use the slightly weirdly named "pattern matching" from C#7 upwards to match on class or structure:

    IObject concrete1 = new ObjectImplementation1();
    IObject concrete2 = new ObjectImplementation2();
    
    switch (concrete1)
    {
        case ObjectImplementation1 c1: return "type 1";         
        case ObjectImplementation2 c2: return "type 2";         
    }
    

提交回复
热议问题