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# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
