What is the difference between Convert and Parse?

前端 未结 4 858
广开言路
广开言路 2020-12-20 22:17

I could write the following to convert an object to an integer.

Convert.ToInt32(myObject);

But I could also write

Int.Parse         


        
4条回答
  •  北海茫月
    2020-12-20 22:50

    According to the documentation, it would depend on the object and whether or not it implements the IConvertible interface. There are a number of reasons that make these approaches different. Notably, if the string representation doesn't represent the corresponding integer value (e.g., "{ Value = 123 }") or the object isn't IConvertible. I would choose using Convert.ToInt32() as the conversion is defined by the type and not relying on some observed property that could change in the future.

提交回复
热议问题