-1

我以前从未见过这个 - C# 中的指针:

public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string> {
    public String(char* value); // <-- string has a constructor that takes a char pointer?
...
}

我很想了解一下。

char 指针是否类似于 C/C++ 中的指针,即与内存位置大小相同的 int 值?

我也想知道是否我缺乏理解指针是为什么我从未完全掌握ref关键字的作用,换句话说,它们是否相关?

4

3 回答 3

3

指针类型是 C# 语言的一部分。它们的工作方式就像 C 中的指针一样,并允许您使用非托管内存、可blittable类型和 blittable 类型数组。它们与 ref/out 参数无关(它们使用托管指针,这是不同的东西)。由于如果使用不当,使用指针会破坏类型安全,因此您只能在不安全的上下文中使用它们。

于 2012-04-15T01:07:52.093 回答
1

指针在我的理解中是用于性能优化的,在这里你闯入“不安全”的领域,直接操作内存地址。

根据我的经验,图像处理是您从指针中获得显着好处的领域之一,例如

http://imrannazar.com/Using-Pointers-in-C

不安全的指针迭代和位图 - 为什么 UInt64 更快?

肯定还有其他典型的场景,但是一个普通的C#应用程序一般来说是不需要指针的。

于 2012-04-15T01:17:44.250 回答
1

C# was designed to simplify memory management to provide programmers which is a quicker and easier way to program. That comes at the cost of performance (and lazy programming) as a garbage disposal has to come by and kill all the broken pointers. For instance, in a game update loop this creates a lot of stuff for the garbage disposal to collect:

       Vector3 myVector;
       void update(int x, int y, int z)
       {
             myVector = new Vector3(x, y, x); //This will kill your Xbox 360 with enough objects
       }

In c# everything is held as a reference. This is a bit different from C/C++ where the programmer has different ways referencing data in RAM.

As a way to provide more flexibly to programmers, especially in areas which require high performance, a programmer is allowed to use pointers and references. This is called "unsafe" variables because it is no longer managed by the garbage disposal. In other words, if there is a memory leak, the garbage disposal will not come by and delete it.

Another reason is for compatibility between C#/C++. If you get into interpolating code between the two languages, you will quickly realize that C# needs to know how to provide compatibly for pointers being passed and obtained by the C++ side. So say if I want to pass C++ code a pointer, I pass

    someInterpatedFunc(ref myVariable);

Hope that answers some questions :)

于 2012-04-15T03:49:04.117 回答