C#中的结构指针初始化 [英] Struct Pointer Initialization in C#

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

问题描述

unsafe public class Temp
{
    public struct Node
    {
        Node *left;
        Node *right;
        int value;
    }

    public Temp()
    {
        Node* T=new Node();
        T->left=null;
        T->right=null;
        T->value=10;
    }
}

main()
{
    Temp temp=new Temp();
}

它给出了错误,即对象引用未设置为对象的实例.当我想制作AVL Tree程序时(我已经在C ++中创建并测试过,但是在C#中复制会产生错误)怎么办?

It gives error that Object reference not set to instance of an object. How can I do it when I want to make AVL Tree Program(which I have created and tested in C++ but copying in C# gives error)

推荐答案

不要像这样在C#中使用指针.如果要移植使用指针作为引用的C ++代码,请改用引用类型.您的代码根本无法使用;一方面,"new"不会在堆外分配结构,即使它确实需要在C#中将指针固定在适当的位置; C#是一种垃圾收集语言.

Don't try to use pointers in C# like this. If you are porting C++ code that uses pointers as references, instead use reference types. Your code will not work at all; "new" does not allocate structs off the heap, for one thing, and even if it did pointers are required to be pinned in place in C#; C# is a garbage-collected language.

简而言之,除非您完全了解C#中有关内存管理的所有知识,否则请不要使用unsafe.您正在关闭保护自己的安全系统,因此您必须知道该安全系统的作用.

In short never use unsafe unless you thoroughly understand everything there is to know about memory management in C#. You are turning off the safety system that is there to protect you, and so you have to know what that safety system does.

代码应为:

public class Temp // safe, not unsafe
{
    public class Node // class, not struct
    {
        public Node Left { get; set; } // properties, not fields
        public Node Right { get; set; } 
        public int Value { get; set; }
    }

    public Temp()
    {
        Node node = new Node();
        node.Left = null; // member access dots, not pointer-access arrows
        node.Right = null;
        node.Value = 10;
    }
}

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

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