What's the difference between casting an int to a string and the ToString() method in C#

后端 未结 6 1707
北海茫月
北海茫月 2020-12-01 17:49

What\'s the difference between casting an Int to a string and the ToString() method ?

For example :-

int MyInt = 10;
label1.Text = (string)MyInt;             


        
6条回答
  •  盖世英雄少女心
    2020-12-01 18:01

    Um, ToString() is calling a method that returns a string representation of the integer.

    When you cast, you are not returning a representation, you are saying that you want to reference the same object (well, value-type in this case) but you want to reference it as a different type.

    A cast will only succeed if the type you are casting to (target type) is the same type as the object being cast or the target type is a superclass or interface of the cast object.

    It is actually possible to do conversion in a cast providing the the source or target type declare implicit or explicit conversions, but the Int32 type does not do this for the String target type.

提交回复
热议问题