Why doesn't C# switch statement allow using typeof/GetType()?

后端 未结 10 2060
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 08:56

As in this example:

switch ( myObj.GetType ( ) )
{
    case typeof(MyObject):
        Console.WriteLine ( \"MyObject is here\" );
        break;
}

10条回答
  •  无人及你
    2020-12-15 09:32

    You could do

    switch ( myObj.GetType().Name )
    {
        case "MyObject":
            Console.WriteLine ( "MyObject is here" );
            break;
    }
    

    This works because switching only works on primitive types (as others have said).

提交回复
热议问题