更改对象指针C#的值

时间:2018-06-03 21:35:41

标签: c# pointers

在C#中可以在不安全的环境中执行此操作:

int number = 2;
WriteLine("Value: " + number); //Print 2

int* ptr = &number;
*ptr = 10;

WriteLine("Value: " + number); //Print 10

但我怎样才能为对象取得同样的效果呢?

var person = new Person("Elena", 20);
Person* ptr = &person; //Error

//void* ptr = &person;
ptr = new Person("Miguel", 30); //Error

在这个例子中看起来是可能的: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/how-to-access-a-member-with-a-pointer

1 个答案:

答案 0 :(得分:0)

您根本无法定义指向ReferenceType的指针。 对于ValueType,您可以使用指针指向它们

int number = 2;
int* ptr = &number; // Allowed

struct Person
{
    float score;
    int age;
}
Person person = new Person();
Person* pp = &person;  // Allowed

struct Person
{
    string name;
    float score;
    int age;
}
Person person = new Person();
Person* pp = &person;  // Not Allowed, Because you can't get pointer to ReferenceType

但是ReferenceType已经是指针但不是unsafe方式,有安全和由GC管理。

class Person
{
    public string name;
    public float score;
    public int age;
}

Person ptr1 = new Person { name="Elena", score= 10, age= 20 };
ptr2 = ptr1;
ptr2.name="Miguel";
Console.WriteLine("Value: " + ptr1.name); // prints Miguel