本文介绍了C# 中有没有像 C++ 一样的指针?安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个使用树数据结构的应用程序.我已经用 C++ 编写了它,现在我想用 C# 编写它.我使用指针来实现树数据结构.C#中也有指针吗?使用它安全吗?
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 structure. Is there a pointer in C# too? Is it safe to use it?
推荐答案
如果您在 C#(或 Java,或许多其他语言)中实现树结构,您将使用引用而不是指针.注意.C++ 中的引用与这些引用不同.
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);
兴趣点:
- 声明成员时无需用
*
修改类型 - 无需在构造函数中将它们设置为 null(它们已经为 null)
- 没有特殊的
->
成员访问运算符 - 无需编写析构函数(虽然查找
IDisposable
)
- 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
)
这篇关于C# 中有没有像 C++ 一样的指针?安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!