什么是铸造在C#中的int为字符串和ToString()方法之间的区别 [英] What's the difference between casting an int to a string and the ToString() method in C#

查看:212
本文介绍了什么是铸造在C#中的int为字符串和ToString()方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是铸造一个Int为字符串和ToString()方法之间的区别?

例如: -

  INT敏= 10;
label1.Text =(字符串)敏; //这不起作用
label1.Text = MyInt.ToString(); //但确实。


解决方案

好了,的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.

这篇关于什么是铸造在C#中的int为字符串和ToString()方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆