在不存在的结构布局中循环 [英] 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;
}
}
问题是错误 Struct member 'info' 在 struct 布局中导致循环.
我在追求类似值类型行为的结构.我可以使用一个类和一个克隆成员函数来模拟这个,但我不明白为什么我需要这样做.
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));
我使用的解决方案是让info"成为一个类而不是一个结构体,并为其提供一个成员函数以返回我在传递它时使用的副本.实际上模拟了与结构相同的行为,但使用了类.
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 个字节,至少一个字节来显示 info
是否为空,加上另一个 info
的大小.这给出了以下不等式:
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.
您必须使用引用类型(即类).您可以使您的类不可变并覆盖 Equals
和 GetHashCode
以提供类似值的行为,类似于 String
类.
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屋!