1.结构是存储在堆栈上的值类型,为什么允许结构的成员中包含引用类型的类?
2.自定义两个类的时候,允许两个类互相作为另一个类的成员:
    public class ClassFirst
    {
        string str;
        classSecond csecond;
    }
    public class classSecond
    {
        string str;
        ClassFirst cfirst;
    }
但是在定义结构的时候为什么不可以:
    public struct structFirst
    {
        string str;
        structSecond sSecond;
    }
    public struct structSecond
    {
        string str;
        structFirst sFirst;
    }
Error 1 Struct member '_th.structFirst.sSecond' of type '_th.structSecond' causes a cycle in the struct layout D:\workSpace\Csharp6th\3th\3th\ClassTemp.cs 11 22 3th
Error 2 Struct member '_th.structSecond.sFirst' of type '_th.structFirst' causes a cycle in the struct layout D:\workSpace\Csharp6th\3th\3th\ClassTemp.cs 16 21 3th

解决方案 »

  1.   

    结构是值类型,在ClassFirst 中定义structSecond sSecond 相当于直接分配了structSecond 的内存,所以会出现在
    structFirst 中分配一个structSecond 大小的内存,所以会出现"causes a cycle in the struct layout"。
    而类是引用类型,在ClassFirst 中定义classSecond csecond相当于在ClassFirst 的内存中申请了一个指针,存放classSecond 的引用地址,叫做csecond,故不会出现cycle 。
      

  2.   

    没啥不可以的,完全可以至于你的代码不行,你看明白那个报错信息了吗?
    Struct member '_th.structFirst.sSecond' of type '_th.structSecond' causes a cycle in the struct 结构体_th.structFirst.sSecond 与 结构体 _th.structSecond 循环定义 public struct structFirst                                   <--|
        {                                                           |
            string str;                                             |
            structSecond sSecond; //调structSecond                  |
        }                                 |                         |
                                          |                         |                    
        public struct structSecond    <—— |                         |
        {                                                           |
            string str;                                             |
            structFirst sFirst; //这里 又回头调structFirst-------------
        } 你这不是双手互博,头尾互咬吗
      

  3.   

    可以嵌套
    但是你的问题是
    Struct member '_th.structFirst.sSecond' of type '_th.structSecond' causes a cycle in the struct结构体 循环嵌套 A调B,B又回头调A,这不是左右互搏,头尾互咬,循环调用是啥
      

  4.   

    至于class行,是因为他是引用类型,对象,在没new之前是不会再内存里分配空间的也就是 B里的A 和 A,并不一定是同一个对象实例但是如果他们是同一实例,你这里同样会出现循环定义的情况比如:csdn有人问过,他在子类的构造函数里new 父类,又在父类的构造函数里new 子类,结果是编译器通过,但是一运行就报 内存溢出错误
      

  5.   

    CSDN这个换行bug还不是一般的大...