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

后端 未结 7 2179
误落风尘
误落风尘 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:25

    You can do the int.TryParse() function:

    int myInt;
    bool parsed = int.TryParse(myVariable, out myInt);
    
    if (parsed) {
        // Do something with myInt or other logic
    }
    
    0 讨论(0)
提交回复
热议问题