我试图了解“this”如何在 C#-6.0 (VS 2015) 中作为属性传递。
using System;
public class Person
{
private Person instance;
public Person()
{
instance = this;
}
public Person myself
{
get { return instance; }
set { instance = value; }
}
public string name = "Eddie";
}
public class Example
{
public static void Main()
{
Person firstPerson = new Person();
Person secondPerson = firstPerson.myself;
secondPerson.name = "Bill";
Console.WriteLine(firstPerson.name);
Console.WriteLine(secondPerson.name);
firstPerson.myself = new Person();
Console.WriteLine(firstPerson.name);
Console.WriteLine(secondPerson.name);
Console.ReadLine();
}
}
我的假设是当行:
Person secondPerson = firstPerson.myself;
运行后,secondPerson 成为对 firstPerson 的引用,因此当我将名称更改为“Bill”时,firstPerson.name
和 secondPerson.name
都是 Bill。但是当我跑的时候
firstPerson.myself = new Person();
我希望 firstPerson.name
和 secondPerson.name
回到“Eddie”,但它仍然是“Bill”。为什么?提前致谢!
最佳答案
您更改了 firstPerson.instance
指向的 Person
实例,但未更改 firstPerson
指向的原始实例。
因此 firstPerson
仍然指向原始的 Person
实例(因此 firstPerson.name
返回第一个实例中设置的值),而 firstPerson.instance
现在指向一个新的(第二个)Person
实例。
Person firstPerson = new Person(); // instance 1
Person secondPerson = firstPerson.myself; // myself refers to instance 1
secondPerson.name = "Bill"; // set name in instance 1
Console.WriteLine(firstPerson.name); // get name from instance 1
Console.WriteLine(secondPerson.name); // get name from myself in instance 1
Console.WriteLine(firstPerson.myself.name); // get name from instance 1 (same as above)
firstPerson.myself = new Person(); // myself refers to instance 2, but firstPerson still refers to instance 1
Console.WriteLine(firstPerson.name); // still getting name from instance 1
Console.WriteLine(secondPerson.name); // still getting name from myself in instance 1
Console.WriteLine(firstPerson.myself.name); // get name from instance 2 (since firstPerson.myself was reassigned)
firstPerson = new Person(); // firstPerson and firstPerson.myself point to instance 3
Console.WriteLine(firstPerson.name); // get name from instance 3, which is the default "Eddie"
Console.WriteLine(secondPerson.name); // still points to instance 1, since that's what it was when it was assigned
Console.WriteLine(firstPerson.myself.name); // get name from instance 3 (since firstPerson.myself is defaults to the new instance again)
关于c# - "this"如何在C#中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56242953/