周期的结构布局不存在 [英] Cycle in the struct layout that doesn't exist
问题描述
这是我的一些代码的简化版本:
This is a simplified version of some of my code:
public struct info
{
public float a, b;
public info? c;
public info(float a, float b, info? c = null)
{
this.a = a;
this.b = b;
this.c = c;
}
}
问题是误差结构成员信息导致在结构布局周期。
像值类型的行为结构后我。我可以模拟这种使用类和克隆成员函数,但我不明白为什么我应该需要。
The problem is the error Struct member 'info' causes a cycle in the struct layout.
I'm after struct like value type behaviour. I could simulate this using a class and a clone member function, but I don't see why I should need to.
这是怎么回事错误真的吗?递归或许会永远的建设在一些类似的情况,但我想不出任何方式,它能够在这种情况下。 。下面举例说明了应该是罚款,如果该程序将汇编
How is this error true? Recursion could perhaps cause construction forever in some similar situations, but I can't think of any way that it could in this case. Below are examples that ought to be fine if the program would compile.
new info(1, 2);
new info(1, 2, null);
new info(1, 2, new info(3, 4));
编辑:
edit:
我使用的解决方案是使信息一类,而不是一个结构,给它一个成员函数返回的,我路过时,它使用的复印。实际上模拟相同的行为作为一个结构,但有一类。
The solution I used was to make "info" a class instead of a struct and giving it a member function to returned a copy that I used when passing it. In effect simulating the same behaviour as a struct but with a class.
我还创建了以下问题,同时寻找一个答案。
I also created the following question while looking for an answer.
推荐答案
这是不合法的拥有包含自身作为成员的结构。这是因为结构具有的固定尺寸,然后它必须至少为每个成员的大小的总和一样大。你的类型就必须有8个字节的两个浮筒,至少有一个字节,以显示是否信息
为空,加上另一个的尺寸信息
。这给了下面的不等式:
It's not legal to have a struct that contains itself as a member. This is because a struct has fixed size, and it must be at least as large as the sum of the sizes of each of its members. Your type would have to have 8 bytes for the two floats, at least one byte to show whether or not info
is null, plus the size of another info
. This gives the following inequality:
size of info >= 4 + 4 + 1 + size of info
这显然是不可能的,因为它需要你的类型是无限大的。
This is obviously impossible as it would require your type to be infinitely large.
您必须使用引用类型(即类)。你可以让你的类不可变的,覆盖等于
和的GetHashCode
给价值类似的行为,类似于字符串
类。
You have to use a reference type (i.e. class). You can make your class immutable and override Equals
and GetHashCode
to give value-like behaviour, similar to the String
class.
这篇关于周期的结构布局不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!