本文介绍了可空类型“int"的默认值是多少?(包括问号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
在 C# 中,int 类型的类实例变量的默认值是多少??
例如,在下面的代码中,如果 MyNullableInt 从未显式赋值,会有什么值?
For example, in the following code, what value will MyNullableInt have if it is never explicitly assigned?
class MyClass
{
public int? MyNullableInt;
}
(似乎答案几乎可以肯定是 null 或 0,但它们中的哪一个?)
(It seems likely that the answer is almost certainly either null or 0, but which of those is it?)
推荐答案
int? 的默认值——以及任何使用type?"的可空类型声明 -- 是 null.
The default value for int? -- and for any nullable type that uses the "type?" declaration -- is null.
为什么会这样:
int?是 Nullable<T>类型的语法糖a>(其中 T 是int),一个结构体.(参考)Nullable<T>类型具有 bool HasValue成员,当false时,使Nullable实例表现得像"一个null值.特别是,Nullable<T>.Equals 方法被覆盖以返回true当HasValue == false的Nullable<T>与实际的null值进行比较时.- 来自 C# 语言规范 11.3.4,结构实例的初始默认值是该结构的所有值类型字段设置为其默认值,并且该结构的所有引用类型字段设置为
null. - C# 中
bool变量的默认值为false(参考).因此,默认Nullable实例的HasValue属性为false;这反过来又使Nullable<T>实例本身的行为类似于null.
int?is syntactic sugar for the type Nullable<T> (where T isint), a struct. (reference)- The
Nullable<T>type has a bool HasValue member, which whenfalse, makes theNullable<T>instance "act like" anullvalue. In particular, the Nullable<T>.Equals method is overridden to returntruewhen aNullable<T>withHasValue == falseis compared with an actualnullvalue. - From the C# Language Specification 11.3.4, a struct instance's initial default value is all of that struct's value type fields set to their default value, and all of that struct's reference type fields set to
null. - The default value of a
boolvariable in C# isfalse(reference). Therefore, theHasValueproperty of a defaultNullable<T>instance isfalse; which in turn makes thatNullable<T>instance itself act likenull.
这篇关于可空类型“int"的默认值是多少?(包括问号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)