What is the default value of the nullable type quot;int?quot; (including question mark)?(可空类型“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"的默认值是多少?(包括问号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可空类型“int"的默认值是多少?(包括问号)?
基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
