Pointer to struct in C# to create a linked list

2020-05-03 01:50发布

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?

4条回答
祖国的老花朵
2楼-- · 2020-05-03 02:09

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楼-- · 2020-05-03 02:09

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.

查看更多
可以哭但决不认输i
4楼-- · 2020-05-03 02:10

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.

查看更多
Animai°情兽
5楼-- · 2020-05-03 02:15

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.

查看更多
登录 后发表回答