这是在阵列的构件的默认值? [英] What is default value of a member in an array?

查看:82
本文介绍了这是在阵列的构件的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我实例化一个数组是这样的:

If I instantiate an array like this:

int array[] = new int[4];

现在,什么是那些4名成员的默认值?它是NULL,0或不存在?

now, what are the default values for those 4 members? Is it null, 0 or not exists?

推荐答案

这是0。它不能为空,为空不是一个有效的 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。

  •   
  • For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).
  • For a variable of a reference-type, the default value is null.

初​​始化为默认值通常由具有内存管理器或垃圾回收器初始化内存所有位归零它被分配使用前完成。出于这个原因,它是方便的使用所有位零重新present空引用

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.

(作为一个实现细节,还有周围的第一点有些trickiness。虽然C#本身不会让你申报值类型参数的构造函数,你的可以的创建您自己的参数的构造函数在IL值类型。我不相信这些构造函数的调用在数组初始化,但他们的将会的在新的X被称为()前pression在C#中,这是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆