如何做一个可空< T>幕后类型的工作? [英] How does a Nullable<T> type work behind the scenes?

查看:187
本文介绍了如何做一个可空< T>幕后类型的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,想知道怎样可空类型在幕后。难道是创建具有空的可能值一个新的对象(对象可以被赋值为null)?

I'm curious to know how the Nullable type works behind the scenes. Is it creating a new object(objects can be assigned null) with a possible value of null?

在这个例子中,我们用一个可空< INT>中是他们的某种隐式转换从对象为int,反之亦然,当你分配给它一个空值

In the example we use a Nullable<int>, is their some kind of implicit conversion from an object to an int and vice versa when you assign it a null value?

我也知道,这可怎么手动创建,是有使用可空类型,而不是创造它我们自己一个benfit?

Also I know how this can be created manually, is there a benfit from using the Nullable type as opposed to creating it ourself?

推荐答案

可空类型是一个结构包括两个字段:一个布尔 T 。当值为null时,布尔是假的和T有默认值。当值不为空,则布尔是真实的。

The nullable type is a struct consisting of two fields: a bool and a T. When the value is null, the bool is false and the T has the default value. When the value is not null, the bool is true.

有使用两个主要好处可空相比,实现自己的功能。还有的语言支持,如ChaosPandion的回答更详细的说明,并有一个事实,即拳击(转换为对象)将自动删除该为空的包装,使无论是空引用或普通的T object.z

There are two main benefits to using Nullable as compared to implementing the functionality yourself. There's the language support, as described in more detail in ChaosPandion's answer, and there's the fact that boxing (converting to an object) will automatically remove the nullable "wrapper", leaving either a null reference or the plain T object.z

这篇关于如何做一个可空&LT; T&GT;幕后类型的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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