Cycle in the struct layout that doesn't exist

后端 未结 5 1011
天命终不由人
天命终不由人 2020-12-03 10:39

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 =         


        
5条回答
  •  春和景丽
    2020-12-03 11:10

    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.

    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.

提交回复
热议问题