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"的默认值是多少?(包括问号)?
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
