Cast versus parse

前端 未结 4 701
广开言路
广开言路 2021-02-14 14:19

I\'ve read a few related questions regarding this topic however none of them are making sense to me. As I understand it, in some cases you can use cast and parse interchangeably

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 14:22

    You generally use Parse() on a string whose value represents a valid value of the type to which you are converting.

    Casting, on the other hand, is better used when you have an object of a derived type but stored in a base variable, and need to use it as its more specific type.

    That is, if you have "1234" you can Parse() that into an int. But if you have

    object variable = 1234;
    

    You should cast it to get it back as an int.

提交回复
热议问题