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"的默认值是多少?(包括问号)?
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
