c# - 在 int 和 string 中装箱和拆箱

标签 c# .net types boxing

我对装箱和拆箱有点困惑。根据其定义

Boxing is implicit conversion of ValueTypes to Reference Types (Object).
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes.

描述这个的最好例子是

int i = 123; object o = i;  // boxing

o = 123; i = (int)o;  // unboxing 

但是我的问题是int是值类型还是string是引用类型所以

int i = 123; string s = i.ToString();

s = "123"; i = (int)s; 

这是装箱拆箱的例子吗???

最佳答案

调用 ToString 不是装箱。它创建一个新字符串,恰好包含您的 int 的文本表示。

当调用 (object)1 时,这会在堆上创建一个包含 int 的新实例。但它仍然是一个 int。 (您可以使用 o.GetType() 进行验证)

String 无法转换为 int。所以你的代码不会编译。

如果您首先将字符串转换为 object,您的代码将编译但在运行时失败,因为您的对象不是装箱的 int。您只能将值类型拆箱为完全正确的类型(或关联的可空类型)。

两个例子:

损坏:

object o=i.ToString();// o is a string
int i2=(int)o;//Exception, since o is no int

工作:

object o=i;// o is a boxed int
int i2=(int)o;//works 

关于c# - 在 int 和 string 中装箱和拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423452/

相关文章:

c# - 没有结果时的 LINQ to SQL 连接

c# - 优雅的方式解析URL

C# 使用线程堆安全地写入文本文件

javascript 动画在 html 页面中工作,但相同的脚本在 .net 页面中不起作用

.net - BindingRedirect 到不同的程序集名称

types - Agda:证明当值相等时,它们的构造函数参数也相等

swift - 字节字符串作为 Swift 4 中的数据

c# - Process.WaitForExit 跨机器不一致

c# - 在 SQL CLR UDF 中使用 System.Linq 程序集

c++ - 结构变量包含什么?