c# - 在完全初始化结构之前访问结构的字段

标签 c# .net struct new-operator

考虑以下代码:

public struct Color {
    public int R;
    public int G;
    public int B;
}

public class App
{
    static void Main()
    {
        Color c;
        c.B = 0xFF;
        int b = c.B;
    }
 }

csc 愉快地编译代码。我一直认为必须先分配结构的所有 字段,然后才能访问该结构的数据成员。这是csc.exe的特长吗?

我认为 NullReferenceExceptions 不是正确的解决方案,因为我们在这里讨论的是结构。

最佳答案

来自 MSDN :

When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

来自 MSDN :

Compiler Error CS0170: Use of possibly unassigned field 'field'. A field in a structure was used without first being initialized. To solve this problem, first determine which field was uninitialized and then initialize it before you try to access it.

来自 MSDN :

Compiler Error CS0165: Use of unassigned local variable 'name'. The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165.


这是错误的:

I always thought all fields of a struct have to be assigned to before one can access data members of the struct

正确的是:

All fields of a struct have to be assigned to before one can access the struct.


Color c;
c.B = 0xFF;
int b = c.B; // Okay. You have assigned B
int r = c.R; // Error CS0170! Use of possibly unassigned field
Color cc = c; // Error CS0165! Use of unassigned local variable. The object cannot be used until all of the fields are initialized

关于c# - 在完全初始化结构之前访问结构的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40069502/

相关文章:

c# - 刷新 DB.designer.cs 文件

c# - HTMLString 序列化为字符串,以 json 编码

c# - vb.net 人工作用域

c - 如何向结构添加多个值

c# - 我应该如何在 .NET Core 2.2 中注册通用接口(interface)

c# - 使用 HTML 帮助程序启动表单的首选方法是什么?

c# - 使用 AutoMapper 进行映射后,如何不丢失目标对象中存在但源对象中不存在的属性

c# - 如何在 Linq to SQL 中合并日期时间偏移量?

在结构内部创建字符串数组

C fread() 一个结构体