为什么会出现在C#类没有循环布局问题? [英] Why is there no cyclic layout issue for classes in C#?
问题描述
公共结构单位
{
单元U;
}
原因:
结构成员Unit.u'类型'单位'的原因在结构中
布局的周期。
块引用>
但
公共类股
{
单元U;
}
编译。我明白了,我想这个问题。引用
单元时
对象,因为它必须初始化另一个成员单位
等无休止的循环便形成了。但为什么编译器限制只为结构
的问题?没有问题持续类
吗?我缺少的东西吗?
解决方案但问题是在以下方面的布局的
在
单位
是一个结构,一个单位的任何值
将不得不包含相同类型的另一个值(以及因此的大小相同),循环往复。这不可能。我想你可能会说,没有其他的领域,为单位等领域
应该不占用内存,因此你的可能的包含它自身内部 - 但我相信CLR的工作方式,确保所有的结构占用至少1字节...
在
单位
是一类,单位
对象只包含一个的参考的另一个单位
对象。无存储问题,并且该值可以为null,开始与
想想这样说:你不能有一个包含来自同一构造的另一家房子蓝图中,但可以肯定,其中包含有类似房子的就可以了...地址
一张纸房子public struct Unit { Unit u; }
Causes:
Struct member 'Unit.u' of type 'Unit' causes a cycle in the struct layout.
But
public class Unit { Unit u; }
compiles. I understand the problem I suppose. An endless cycle will be formed when referencing a
Unit
object since it will have to initialize another memberUnit
and so on. But why does the compiler restrict the problem just forstructs
? Doesn't the issue persist forclass
too? Am I missing something?解决方案The problem is in terms of layout.
When
Unit
is a struct, any value for aUnit
would have to contain another value of the same type (and thus the same size), ad infinitum. That's impossible. I suppose you could argue that with no other fields, the fields forUnit
should take up no memory, so you could contain it within itself - but I believe the way the CLR works ensures that all structs take up at least 1 byte...When
Unit
is a class, aUnit
object only has to contain a reference to anotherUnit
object. No storage problems, and the value can be null to start with.Think of it this way: you can't have a house which contains another house constructed from the same blueprint, but you can certainly have a house which contains a piece of paper with a similar house's address on it...
这篇关于为什么会出现在C#类没有循环布局问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!