Can I check if a variable can be cast to a specified type?

后端 未结 7 2224
误落风尘
误落风尘 2020-12-15 15:50

I am trying to verify whether a variable that is passed can be converted to a specific type. I have tried the following but can\'t get it to compile so I assume I\'m going

7条回答
  •  余生分开走
    2020-12-15 16:11

    I know it's quite old but for someone looking for answer in modern way will leave post with response. From C#7 You can use new switch with pattern matching (https://docs.microsoft.com/pl-pl/dotnet/csharp/pattern-matching)

            switch (myObject)
            {
                case PlayerObject playerObject:
                    //this is player object type and can use also playerObject because it's already casted
                    break;
                case EnemyObject enemyObject:
                    //same here but we have enemy object type
                    break;
                default:
                    break;
            }
    

提交回复
热议问题