Pointer to struct in C# to create a linked list

2020-05-03 01:41发布

问题:

C# does not like pointers, but I need to use them now to create a linked list, like we would do in C. The struct is simple:

    public unsafe struct Livro
    {
        public string name;
        public Livro* next;
    }

But I get the error: "Cannot take the address of, get the size of, or declare a pointer to a managed type". Any ideas?

回答1:

You can just use a class instead of a struct:

public class Livro
{
    public string Name { get; set; }
    public Livro Next { get; set; }
}

This will provide the proper behavior automatically.

That being said, you might want to just use the LinkedList<T> class from the framework directly.



回答2:

The problem is the string declaration. You have to go low level and use char* pointers. Using unsafe comes with all the headaches of leaving the managed world...



回答3:

Any ideas?

Use a class instead of a struct and then the pointer becomes a reference:

public class Livro
{
    public string name;
    public Livro next;
}

And then it would be a good idea to use properties instead of public fields.



回答4:

you can do it with struct like this:

struct LinkedList
{
    public int data;
    public LinkedListPtr next;
    public class LinkedListPtr
    {
        public LinkedList list;
    }
}

or like this:

struct LinkedList
{
    public int data;
    public LinkedList[] next;
}

but it's better to just use class for the linked list instead.