可空类型“int"的默认值是多少?(包括问号)?

3

本文介绍了可空类型“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;
}

(似乎答案几乎可以肯定是 null0,但它们中的哪一个?)

(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>(其中 T 是 int),一个结构体.(参考)
  • Nullable<T> 类型具有 bool HasValue成员,当 false 时,使 Nullable 实例表现得像"一个 null 值.特别是,Nullable<T>.Equals 方法被覆盖以返回 trueHasValue == falseNullable<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 is int), a struct. (reference)
  • The Nullable<T> type has a bool HasValue member, which when false, makes the Nullable<T> instance "act like" a null value. In particular, the Nullable<T>.Equals method is overridden to return true when a Nullable<T> with HasValue == false is compared with an actual null 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# is false (reference). Therefore, the HasValue property of a default Nullable<T> instance is false; which in turn makes that Nullable<T> instance itself act like null.

这篇关于可空类型“int"的默认值是多少?(包括问号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14