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

Accessing fields of structs before completely initializing the struct

考虑以下代码:

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愉快地编译代码。我一直认为必须先分配结构的 all 字段,然后才能访问结构的数据成员。这是csc.exe的特长吗?

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

参考这个link

msdn ink

如果您使用 Color c; 字段不会被初始化,但是如果您使用 Color c = new Color(); 所有字段都将被初始化。

如果你 运行 下面的代码。它将无法编译。

    Color c;
    int b = c.B;

但这会被编译。

       Color c = new Color();
       // c.B = 0xFF;
        int b = c.B;

来自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