简体   繁体   中英

c# struct with reference to struct

I got a structure called TWord defined like that:

struct TWord{
    public string Text
    /*Some more stuff*/

    public TWord(string fText){this.Text = fText;}
}

A word is a word in a text. Now, I'd like to insert two references of TWord in the struct TWord. It should look like this:

struct TWord{
    public string Text
    public TWord PreviousWord;
    public TWord NextWord;

    public TWord(string fText, ref TWord fPreviousWord = null, ref TWord fNextWord = null){ 
        this.Text = fText; 
        this.PreviousWord = fPreviousWord;
        this.NextWord = fNextWord;
    }
}

In C++, this is no problem, but does not work in C#. I get the error Struct member TWord.PreviousWord of type TWord causes a cycle in the struct layout.

How can I do that in C#?

Structs in general are for smaller object - some say under 16bytes - for your application a struct is inappropriate only by the size in memory that it can take up. Struct are supposed to be simple and small data carriers. If you want to make bigger structures that also recursively call stuff or can contain bigger lists you should use classes . This all is discussed here Choosing Between Class and Struct .

In your case I would even suggest you use a List<strings> or a List<World> you are refering to the next and previous item which is exactly what a List does. You can move next, and using the c5 collection libary equivalent youre also allowed to move back. (Alternatively you can buffer the List to achieve the same effect).

Using existing and well optimized libaries will safe you some hassle and genrally make your code look clear and run faster, therefore I would advice you to do so wherever you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM