Is there pointer in C# like C++? Is it safe?

后端 未结 5 1541
抹茶落季
抹茶落季 2020-12-08 18:20

I\'m writing an application that work with a tree data structure. I\'ve written it with C++, now i want to write it by C#. I use pointers for implementing the tree data stru

5条回答
  •  我在风中等你
    2020-12-08 19:08

    If you're implementing a tree structure in C# (or Java, or many other languages) you'd use references instead of pointers. NB. references in C++ are not the same as these references.

    The usage is similar to pointers for the most part, but there are advantages like garbage collection.

    class TreeNode
    {
        private TreeNode parent, firstChild, nextSibling;
    
        public InsertChild(TreeNode newChild)
        {
            newChild.parent = this;
            newChild.nextSibling = firstChild;
            firstChild = newChild;
        }
    }
    
    var root = new TreeNode();
    var child1 = new TreeNode();
    root.InsertChild(child1);
    

    Points of interest:

    • No need to modify the type with * when declaring the members
    • No need to set them to null in a constructor (they're already null)
    • No special -> operator for member access
    • No need to write a destructor (although look up IDisposable)

提交回复
热议问题