gpt4 book ai didi

c# - 创建具有固定大小数组的不安全结构时,数组是否初始化为默认值?

转载 作者:行者123 更新时间:2023-12-04 01:53:53 26 4
gpt4 key购买 nike

考虑以下代码:

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.



现在,我自己还没有测试过,这些规范的语言有时很难完全理解。但是,这似乎与您的发现一致

关于c# - 创建具有固定大小数组的不安全结构时,数组是否初始化为默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51665717/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com