c#是否可以获取对象的引用,获取对象本身并进行更改,而不是分配给新对象?

Coo*_*Bro 3 c# reference object assign

我很好奇是否可以在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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

如果你的意思是"我可以改变值a来引用不同的对象,只需改变它的值b吗?" 然后答案是否定的.

重要的是要理解变量的值永远不是对象 - 始终是值类型值或引用.我喜欢把像纸片这样的变量和像房子这样的物体想象出来.

一张纸可以在其上写上值类型值(例如数字)或房屋的地址.当你写:

var b = a;
Run Code Online (Sandbox Code Playgroud)

这是创建一张新的纸张(b)并将在纸张a上写的内容复制到纸张上b.那时你可以做两件事:

  • 改变所写的内容b.这不会影响a切向上写的内容
  • 转到写在上面的地址b,并修改房屋(例如,绘制前门).这并没有改变所写的内容a,但它确实意味着当你访问写在a你写的地址时,你会看到变化(因为你要去同一所房子).

这是假设"常规"变量,请注意 - 如果使用ref参数,则有效地将一个变量作为另一个变量的别名.例如:

Test a = new Test("Original");
ChangeMe(ref a);
Conosole.WriteLine(a.TestString); // Changed

...

static void ChangeMe(ref Test b)
{
    b = new Test("Changed"); // This will change the value of a!
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们有效地拥有一张纸,名称a(在调用代码中) b(在方法中).

  • @CoolCodeBro:不,`a`是变量,`b`是变量.他们的*值*是参考. (2认同)