编译器错误 CS0523

“struct1”类型的结构成员“struct2 field”在结构布局中导致循环

一个或多个结构的定义包括形成循环的递归引用。 此限制仅适用于结构,因为结构是值类型。 若要创建递归引用,请将类型声明为作为引用类型的类。

示例 1

以下示例演示自引用类型如何导致生成 CS0523:

// CS0523.cs
// compile with: /target:library
struct SelfReferentialStruct
{
    public SelfReferentialStruct other;   // CS0523
}

class SelfReferentialClass
{
    public SelfReferentialClass other;   // OK
}

创建自引用结构类型时,它包含的副本类型与成员类型相同。 但是,该成员随后有另一个副本,该副本以递归方式继续。 循环的结果是无法确定类型的大小并发出 CS0523。

示例 2

以下示例演示类型引用循环如何导致生成 CS0523:

// CS0523b.cs
// compile with: /target:library
struct ReferenceCycleStruct1
{
    public ReferenceCycleStruct2 other;   // CS0523
}

struct ReferenceCycleStruct2
{
    public ReferenceCycleStruct3 other;   // CS0523
}

struct ReferenceCycleStruct3
{
    public ReferenceCycleStruct1 other;   // CS0523
}

要解决上述错误,可以调整引用,使循环不再形成,或将至少一种结构类型转换为类。 与上一个示例类似,ReferenceCycleStruct1 包含 ReferenceCycleStruct2ReferenceCycleStruct2 包含 ReferenceCycleStruct3,而 ReferenceCycleStruct3 又再次包含 ReferenceCycleStruct1