拳击/拆箱和可空? [英] Boxing/Unboxing and Nullable?

查看:119
本文介绍了拳击/拆箱和可空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,装箱和拆箱是关于铸造(实型对象...对象实型)。但我不明白的MSDN说什么关于它的可空。这是我不明白的文字:

I understand that boxing and unboxing is about casting (real type to object... object to real type). But I do not understand what the MSDN say about it with the Nullable. Here is the text I do not understand:

在可空类型进行装箱时,公共语言运行库自动箱可空对象的基础值,而不是可空对象本身。也就是说,如果HasValue属性为true,则Value属性的内容装箱。当可空类型的基础值为拆箱,公共语言运行库创建初始化为基础值一个新的可空结构。 来源

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable structure initialized to the underlying value. Source

当你改变你的对象为实型,这是为空的真正类型变量将是对象的类型?我不明白这一点?

When you change your object to a real type, the real type variable that was nullable will be the type of object? I do not get it?

推荐答案

一下它的意思是,如果你做的:

What it's saying is that if you do:

int? x = 5;
object y = x; // Boxing

您结束了一个盒装 INT ,不是盒装可空< INT> 。同样,如果你这样做:

You end up with a boxed int, not a boxed Nullable<int>. Similarly if you do:

int? x = null; // Same as new Nullable<int>() - HasValue = false;
object y = x; // Boxing

则Y最终为一个空引用。

Then y ends up as a null reference.

这篇关于拳击/拆箱和可空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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