可空类型“int?”的默认值是什么? (包括问号)? [英] What is the default value of the nullable type "int?" (including question mark)?
本文介绍了可空类型“int?”的默认值是什么? (包括问号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,类型 int的类实例变量的默认值是什么?
?
For例如,在以下代码中, 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
.
为什么会出现这种情况:
Why this is the case:
-
int?
是 Nullable< T> (其中T是int
),一个结构。 (参考) -
Nullable< T>
类型有一个 bool HasValue 成员,其中当false
时,使Nullable< T>
实例表现得像一个null
价值。特别是,重写 Nullable< T> .Equals方法以返回true
当Nullable< T>
与HasValue == false
进行比较时实际null
value。 - 来自 C#语言规范11.3.4 ,结构实例的初始默认值是所有结构的值类型字段设置为其默认值,以及所有结构的引用类型字段设置为
null
。 - C#中
bool
变量的默认值为false
(< a href =https://msdn.microsoft.com/en-us/library/c8f5xwh7.aspx>参考)。因此,默认Nullable< T>
实例的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" anull
value. In particular, the Nullable<T>.Equals method is overridden to returntrue
when aNullable<T>
withHasValue == false
is compared with an actualnull
value. - 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
bool
variable in C# isfalse
(reference). Therefore, theHasValue
property of a defaultNullable<T>
instance isfalse
; which in turn makes thatNullable<T>
instance itself act likenull
.
这篇关于可空类型“int?”的默认值是什么? (包括问号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文