c#是否可以获取对象的引用,获取对象本身并进行更改,而不是分配给
发布时间:2020-12-16 01:57:28 所属栏目:百科 来源:网络整理
导读:我很好奇是否可以在c#中使用类似的东西.我不知道为什么有人想这样做,但如果能做到这一点仍然很有意思: public class Test{ public string TestString { private set; get; } public Test(string val) { TestString = val; }} public class IsItPossible { p
我很好奇是否可以在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"); } } 解决方法
如果你的意思是“我可以改变a的值来引用不同的对象,只需改变b的值吗?”然后答案是否定的.
重要的是要理解变量的值永远不是对象 – 始终是值类型值或引用.我喜欢把像纸片这样的变量和像房子这样的物体想象出来. 一张纸可以在其上写上值类型值(例如数字)或房屋的地址.当你写: var b = a; 这是创建一张新纸(b)并将在纸张a上写的内容复制到纸张b上.那时你可以做两件事: >改变写在b上的内容.这不会影响切向均匀写的内容 这是假设“常规”变量,请注意 – 如果使用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! } 在这里,我们实际上有一张纸,名称为a(在调用代码中)和b(在方法中). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |