更新时间:2023-10-27 09:17:40
好了,的ToString()
只是一个方法调用返回的字符串。它在对象定义
所以它总是有效的任何东西(除了一个空引用除外)打电话。
转换操作符可以做的四件事之一:
INT
到字节
对象
到字符串
,检查目标对象是一个合适的类型对象
到 INT
在这种情况下,你问的编译器发出code从 INT
转换为字符串
。以上方案都不适用,所以你得到一个编译时错误。
What's the difference between casting an Int to a string and the ToString() method ?
For example :-
int MyInt = 10;
label1.Text = (string)MyInt; // This Doesn't Work
label1.Text = MyInt.ToString(); // but this does.
Well, ToString()
is just a method call which returns a string. It's defined in object
so it's always valid to call on anything (other than a null reference).
The cast operator can do one of four things:
int
to byte
object
to string
, which checks for the target object being an appropriate typeobject
to int
In this case, you're asking the compiler to emit code to convert from int
to string
. None of the above options apply, so you get a compile-time error.