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?
相关问题
- Sorting 3 numbers without branching [closed]
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- How to compile C++ code in GDB?
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.
Points of interest:
*
when declaring the members->
operator for member accessIDisposable
)YES. There are pointers in C#.
NO. They are NOT safe.
You actually have to use keyword
unsafe
when you use pointers in C#.For examples look here and MSDN.
Use this instead and code will be SAFE and CLEAN.
Yes, declared using the syntax
int* varName;
.No pointers are not safe.
There are safe ways to construct a data structure without pointers. If the nodes are classes, then they'll automatically be reference types so you don't need any pointers. Otherwise, you can box them into a reference.
Yes, there is a pointer: IntPtr
Wikipedia: "which is a safe managed equivalent to int*, and does not require unsafe code"
There is a great series of Data Structures implemented in .Net 2 on MSDN.
Data Structures Part 1
They include sample code for things like Binary Search Tree, Graph, SkipList, NodeList, etc. The code is quite complete and includes a number of pages of docs about why these structures work, etc.
None of the ones from Microsoft use pointers. In general you never NEED to use them in C#. There are times when using them would be nice, or they are just the way you think from C++. But you can usually find a way not to use them.
The biggest reasons why not to use unsafe code for pointers is that you lose Medium Trust compliance. You can't run through mechanisms like click once, asp.net websites, and Silverlight doesn't allow them either. Stick with refs and fully managed concepts to ensure your code can run in more places.