数组中成员的默认值是多少? [英] What is the default value of a member in an array?
问题描述
我像这样实例化一个数组:
I instantiate an array like this:
int array[] = new int[4];
这四个成员的默认值是多少?是否为空、0 或不存在?
What are the default values for those four members? Is it null, 0 or not exists?
推荐答案
它是 0.它不能为 null,因为 null 不是一个有效的 int
值.
It's 0. It can't be null, as null isn't a valid int
value.
来自 C# 5 规范的第 7.6.10.4 节:
From section 7.6.10.4 of the C# 5 specification:
新数组实例的所有元素都初始化为其默认值(第 5.2 节).
All elements of the new array instance are initialized to their default values (§5.2).
来自第 5.2 节:
变量的默认值取决于变量的类型,确定如下:
The default value of a variable depends on the type of the variable and is determined as follows:
- 对于值类型的变量,默认值与值类型的默认构造函数计算的值相同(第 4.1.2 节).
- 对于引用类型的变量,默认值为空.
默认值的初始化通常是通过让内存管理器或垃圾收集器在分配使用之前将内存初始化为所有位为零来完成的.为此,使用所有位为零来表示空引用很方便.
Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference.
(作为一个实现细节,围绕第一个要点有一些技巧.尽管 C# 本身不允许您为值类型声明无参数构造函数,但您可以为它创建自己的无参数构造函数IL 中的值类型.我不相信这些构造函数在数组初始化中被调用,但它们将在 C# 中的 new X()
表达式中被调用.它在不过,确实是 C# 规范的领域.)
(As an implementation detail, there's some trickiness around the first bullet point. Although C# itself doesn't allow you to declare a parameterless constructor for value types, you can create your own parameterless constructors for value types in IL. I don't believe those constructors are called in array initialization, but they will be called in a new X()
expression in C#. It's outside the realm of the C# spec though, really.)
这篇关于数组中成员的默认值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!