数组中成员的默认值是什么? [英] What is the default value of a member in an array?
问题描述
我实例化一个这样的数组:
I instantiate an array like this:
int array[] = new int[4];
这四个成员的默认值是多少?是null,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节)计算的值相同.
- 对于引用类型的变量,默认值为null.
初始化默认值通常是通过让内存管理器或垃圾回收器在分配内存之前将内存初始化为全零位来完成的.因此,使用全零位来表示空引用很方便.
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()
表达式中调用. )
(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屋!