且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是铸造在C#中的int为字符串和ToString()方法之间的区别

更新时间:2023-10-27 09:17:40

好了,的ToString()只是一个方法调用返回的字符串。它在对象定义所以它总是有效的任何东西(除了一个空引用除外)打电话。

转换操作符可以做的四件事之一:


  • 系统predefined转换,例如 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:

  • A predefined conversion, e.g. int to byte
  • An execution time reference conversion which may fail, e.g. casting object to string, which checks for the target object being an appropriate type
  • A user-defined conversion (basically calling a static method with a special name) which is known at compile-time
  • An unboxing conversion which may fail, e.g. casting object 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.