Pointer to struct in C# to create a linked list

孤人 提交于 2019-12-02 17:19:33

问题


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.



来源:https://stackoverflow.com/questions/16551182/pointer-to-struct-in-c-sharp-to-create-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!