指向 C# 中结构的指针以创建链表 [英] Pointer to struct in C# to create a linked list

查看:22
本文介绍了指向 C# 中结构的指针以创建链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 不喜欢指针,但我现在需要使用它们来创建一个链表,就像我们在 C 中所做的那样.结构很简单:

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?

推荐答案

你可以只使用 class 而不是 struct :

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.

话虽如此,您可能只想使用 LinkedList 直接来自框架的类.

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

这篇关于指向 C# 中结构的指针以创建链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆