使用 C# 结构体在域模型中循环引用
当两个结构之间存在循环引用时会发生什么?对于下面的示例,内存分配是如何工作的,或者会产生错误吗?
public struct MultipleChoiceQuestion
{
public IEnumerable<Option> Options;
}
public struct Option
{
public MultipleChoiceQuestion Question;
}
What happens when there is a circular reference between two structs? How does memory allocation work for the example below or would it yield and error?
public struct MultipleChoiceQuestion
{
public IEnumerable<Option> Options;
}
public struct Option
{
public MultipleChoiceQuestion Question;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MultipleChoiceQuestion
中的Options
字段只是一个参考,默认情况下为null
。Option
中的Question
字段是一个MultipleChoiceQuestion
类型的值,默认情况下将具有默认值。这里没有问题(除了在多种方面存在问题的设计之外)。导致逻辑内存问题的真正循环引用将无法编译:
The
Options
field inMultipleChoiceQuestion
is just a reference here, which will benull
by default. TheQuestion
field inOption
is a value of typeMultipleChoiceQuestion
which will have its default value by default. There's no problem here (other than a questionable design in more ways than one).A genuine circular reference leading to a logical memory problem will fail to compile:
问题(属性)是封装;问题是外部结构的一部分,通过字段。
然而,选项是对产生一个或多个选项的外部对象的引用;每次都会复制这些内容。
这里还有其他几个错误:
:
Question (property) is encapsulation; the question is part of the outer struct, via a field.
Options, however, is a reference to an external object that yields one or more Options; these will be copied each time.
There are several other mistakes here:
IMO:
MultipleChoiceQuestion
将仅具有对 IEnumerable 对象的引用(指针),因此堆栈上该结构的大小将是单个 IntPtr(在 x86 计算机上为 4 个字节)。Option
结构将具有相同的大小,因为它仅包含MultipleChoiceQuestion
结构。The
MultipleChoiceQuestion
will simply have a reference (pointer) to an object that is IEnumerable, so the size of that struct on the stack will be a single IntPtr (4 bytes on an x86 machine).The
Option
struct will have the same size, because it contains only theMultipleChoiceQuestion
struct.