使用固定大小的数组创建不安全结构时,数组是否初始化为默认值?
When creating an unsafe struct with a fixed size array, is the array initialized to default values?
考虑以下代码:
public unsafe struct MyStruct
{
public fixed int Nums[128];
}
private static void DoSomething()
{
MyStruct s = new MyStruct();
unsafe
{
int val = s.Nums[23];
Console.WriteLine(val.ToString()); //Is this guaranteed to be "0"?
}
}
这样的话,是不是保证在创建新的MyStruct
时,每个索引处的Nums
的值都是0?
在我自己的测试中,它似乎确实被初始化为默认值,但我问是因为它是 unsafe
。
啊好的,这花了一些时间才找到,
但是从 Language Specification Version 3.0
从 18.7 个固定大小缓冲区开始 并继续
有几个参考文献,最值得注意的
Fixed size buffers are not subject to definite assignment checking
(§5.3), and fixed size buffer members are ignored for purposes of
definite assignment checking of struct type variables. When the
outermost containing struct variable of a fixed size buffer member is
a static variable, an instance variable of a class instance, or an
array element, the elements of the fixed size buffer are automatically
initialized to their default values (§5.2). In all other cases, the
initial content of a fixed size buffer is undefined.
现在,我还没有亲自测试过,这些规范的语言有时很难完全理解。然而,这似乎与您的发现一致
考虑以下代码:
public unsafe struct MyStruct
{
public fixed int Nums[128];
}
private static void DoSomething()
{
MyStruct s = new MyStruct();
unsafe
{
int val = s.Nums[23];
Console.WriteLine(val.ToString()); //Is this guaranteed to be "0"?
}
}
这样的话,是不是保证在创建新的MyStruct
时,每个索引处的Nums
的值都是0?
在我自己的测试中,它似乎确实被初始化为默认值,但我问是因为它是 unsafe
。
啊好的,这花了一些时间才找到,
但是从 Language Specification Version 3.0
从 18.7 个固定大小缓冲区开始 并继续
有几个参考文献,最值得注意的
Fixed size buffers are not subject to definite assignment checking (§5.3), and fixed size buffer members are ignored for purposes of definite assignment checking of struct type variables. When the outermost containing struct variable of a fixed size buffer member is a static variable, an instance variable of a class instance, or an array element, the elements of the fixed size buffer are automatically initialized to their default values (§5.2). In all other cases, the initial content of a fixed size buffer is undefined.
现在,我还没有亲自测试过,这些规范的语言有时很难完全理解。然而,这似乎与您的发现一致