Struct Pointer Initialization in C#

强颜欢笑 提交于 2019-12-06 02:38:16

问题


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();
}

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)


回答1:


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.

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.

The code should be:

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;
    }
}



回答2:


The problem is with the line:

Node* T=new Node();

In C#, new Node() returns Node (which is reference), not Node* (which is pointer). You should use stackalloc, instead.

Anyway, please do not copy C++ and do it C# way!




回答3:


You cannot assign a .NET variable to a pointer you can only take it's address. If you do not reference a newed Node it gets garbage collected immediately, therefore you've probably ran into "object reference not set". Expression like Node* T = new Node() should not compile however, since it effectively tries to do an invalid type conversion.

What you are trying to do is wrong: do not copy and paste C++ code to C#, this is nonsense. If you already got tested C++ components use .NET/unmanaged interop to marshal data between the two worlds, though I would not recommend to do it at this level of abstraction. If you're doing an exercise, implement an AVL tree in .NET world only, otherwise use one of the framework collections with equivalent functionality e.g. SortedSet or SortedDictionary...



来源:https://stackoverflow.com/questions/8687529/struct-pointer-initialization-in-c-sharp

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