使用UnSafe代码使指针移动到自定义类的下一个元素

use*_*024 0 c# pointers unsafe

是否可以在C#中执行以下操作?

unsafe string GetName()
{
    Foo[] foo = new Foo[2]; // Create an array of Foo and add two Foo elements
    foo[0] = new Foo { Name = "Bob" };
    foo[1] = new Foo { Name = "Jane" };

    Foo *ptr = &foo;    // Get address of the first element in the array
    ptr++;  // Move to the next element in the array

    return *ptr.Name;  // Expect Name to be "Jane"
}
Run Code Online (Sandbox Code Playgroud)

我正在玩自定义数据结构,我希望能够做到这一点.

我知道你可以用int类型等来做,但是用户定义的结构和类呢?

Eri*_*ert 7

您可以这样做,但Foo前提是所有字段都是"非托管类型"的结构. int是一种非托管类型; string不是.您应该使用该fixed语句来修复数组,以便垃圾收集器不会移动它.请参阅规范的第18章,并注意当您关闭安全系统时,它会关闭.这意味着当您编写不安全的代码时,您有责任了解C#中有关内存管理的所有内容.你了解内存管理的一切吗?如果答案是"否",那么就做我做的事:不要写不安全的代码.我已经编写C#代码十年了,并且还没有编写不安全的代码(除了编译器测试用例).

你不应该首先这样做.没有必要使用不安全的代码.如果你想要的东西就像一个指向数组中间的指针,你可以在不使用指针的情况下以类型安全的方式做到这一点.

在这里,我甚至为你编写了代码:

http://blogs.msdn.com/b/ericlippert/archive/2011/03/10/references-and-pointers-part-two.aspx