我只是好奇,如果這樣的事情可能在C#中。我不知道爲什麼會有人想這樣做,但它仍然是有趣的,如果是可以做的:c#是否有可能獲取對象的引用,獲取對象本身並對其進行更改,而不是分配給新對象?
public class Test
{
public string TestString { private set; get; }
public Test(string val) { TestString = val; }
}
public class IsItPossible
{
public void IsItPossible()
{
Test a = new Test("original");
var b = a;
//instead of assigning be to new object, I want to get where b is pointing and change the original object
b = new Test("Changed"); // this will assign "b" to a new object", "a" will stay the same. We want to change "a" through "b"
//now they will point to different things
b.Equals(a); // will be false
//what I'm curious about is getting where b is pointing and changing the object itself, not making just b to point to a new object
//obviously, don't touch a, that's the whole point of this challenge
b = a;
//some magic function
ReplaceOriginalObject(b, new Test("Changed"));
if (a.TestString == "Changed" && a.Equals(b)) Console.WriteLine("Success");
}
}
我不這麼認爲,但我認爲它也不重要。當您創建新對象並將變量指向新對象(堆上的新空間)時,如果沒有引用舊對象(堆中的舊空間),則垃圾收集器將很快將其清除,從而離開你在一個邏輯上等於你想要達到的狀態。 – David
在線上'b = new Test(「Changed」);'你在哪裏說'「//這會將」b「分配給一個新對象」,從技術上講,你應該說「//這會給一個新對象賦予」b 「 ' –
創建一個新對象的條件之一嗎?如果沒有,b = a;然後是b.TestString =」已更改「將改變對象的值,儘管你只有一個。 – Alvaro