为什么会出现在C#类没有循环布局问题? [英] Why is there no cyclic layout issue for classes in C#?

查看:271
本文介绍了为什么会出现在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 member Unit and so on. But why does the compiler restrict the problem just for structs? Doesn't the issue persist for class too? Am I missing something?

解决方案

The problem is in terms of layout.

When Unit is a struct, any value for a Unit 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 for Unit 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, a Unit object only has to contain a reference to another Unit 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆