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
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
structFirst 中分配一个structSecond 大小的内存,所以会出现"causes a cycle in the struct layout"。
而类是引用类型,在ClassFirst 中定义classSecond csecond相当于在ClassFirst 的内存中申请了一个指针,存放classSecond 的引用地址,叫做csecond,故不会出现cycle 。
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-------------
} 你这不是双手互博,头尾互咬吗
但是你的问题是
Struct member '_th.structFirst.sSecond' of type '_th.structSecond' causes a cycle in the struct结构体 循环嵌套 A调B,B又回头调A,这不是左右互搏,头尾互咬,循环调用是啥