gpt4 book ai didi

c# - .NET 中用户创建的结构和框架结构之间的差异

转载 作者:太空狗 更新时间:2023-10-29 19:57:40 26 4
gpt4 key购买 nike

为什么 C# 编译器不允许你编译它:

int a;
Console.WriteLine(a);

但允许你编译:

MyStruct a;
Console.WriteLine(a);

其中 MyStruct 定义为:

struct MyStruct
{

}

更新:在第一种情况下,错误是:

Error 1 Use of unassigned local variable 'a'

最佳答案

C# 不允许读取未初始化的局部变量。这是 language specification 的摘录适用于这种情况:

5.3 Definite assignment

...

A struct-type variable is considereddefinitely assigned if each of itsinstance variables is considereddefinitely assigned.


显然,由于您的结构没有字段,所以这不是问题;它被认为是明确分配的。向其中添加一个字段应该会破坏构建。

有点相关的说明:

11.3.8 Constructors

No instance member function can be called until all fieldsof the struct being constructed havebeen definitely assigned.

关于c# - .NET 中用户创建的结构和框架结构之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4268452/

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