【发布时间】:2013-10-02 20:28:58
【问题描述】:
我只是好奇在 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");
}
}
【问题讨论】:
-
我不这么认为,尽管我认为这也不重要。当您创建新对象并将变量指向新对象(堆上的新空间)时,如果没有任何东西引用旧对象(堆上的旧空间),那么垃圾收集器将迅速摆脱它,留下你在逻辑上等于你想要达到的状态。
-
在线
b = new Test("Changed");你说“//这会将“b”分配给一个新对象”,从技术上讲,您应该说“//这会将一个新对象分配给“b”` -
创建新对象是条件之一吗?如果不是,b = a;后面跟着 b.TestString = "Changed" 会改变对象的值。虽然你只有一个。
-
@alvaro 是的。它想替换对象本身,而不仅仅是它的部分。
-
@CoolCodeBro 那么,这是不可能的。 C# 不允许你改变这种指针
标签: c# object reference assign