문제

Is it possible to do something like the following in 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"
}

I'm playing around with custom data structures, and I would like to be able to do this.

I know you can do it with int types etc, but what about user defined structs and classes?

도움이 되었습니까?

해결책

You can do this, but only if Foo is a struct where all the fields are "unmanaged types". int is an unmanaged type; string is not. You should use the fixed statement to fix the array in place so that the garbage collector does not move it. Consult chapter 18 of the specification, and note that when you turn the safety system off, it is off. That means that you are responsible for understanding everything about memory management in C# when you write unsafe code. Do you understand everything about memory management? If the answer is "no" then do what I do: don't write unsafe code. I've been writing C# code for ten years and haven't had to write unsafe code (aside from compiler test cases) yet.

You simply should not do this in the first place. There's no need to use unsafe code. If you want something that acts like a pointer to the middle of an array you can do that in a typesafe manner without using pointers.

Here, I've even written the code for you:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top