Why can't you declare a static struct in C#, but they can have static methods?

前端 未结 3 1398
执念已碎
执念已碎 2020-12-13 09:31
// OK
struct MyStruct
{
    static void Foo() { }
}

// Error
static struct MyStruct
{
}
3条回答
  •  天涯浪人
    2020-12-13 09:59

    The key point here is that the static modifier on a class enforces (among other things) that an instance of the class cannot be created. This is done by forcing a private constructor.

    The CLR doesn't have any way to prevent an instance of a struct type from being created. Even if there is no public default constructor, simply declaring

    struct S { }
    
    S[] items = new S[]{1};
    

    would create an instance of the struct with all of the associated memory set to zero bits.

    Note that this is different from a reference type (class), where the same code would create a reference of the specified type (referencing no object aka null) but not an instance of the object itself.

提交回复
热议问题