本文主要是介绍关于var1=var2=something赋值语句的思考,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
刚才在阅读《c#本质论》一书时,开头有提到var1=var2=something的赋值体,之前也曾用过(但是个人不建议这么使用),但是没有认真思考这种赋值方式的本质问题,即:var1是对var2的引用还是对something的引用。后面我编写了一些PoC代码对此进行验证。
代码片段1:
#region TestStringstring str1, str2;//str1 = str2 = "This is a test string...";str2 = "This is a test string...";str1 = str2;Console.WriteLine("Str1: " + str1);Console.WriteLine("Str2: " + str2);str2 = "This is another test string...";Console.WriteLine();Console.WriteLine("Str1: " + str1);Console.WriteLine("Str2: " + str2);#endregion
输出的结果是:
Str1: This is a test string...
Str2: This is a test string...
Str1: This is a test string...
Str2: This is another test string...
还是
Str1: This is a test string...
Str2: This is a test string...
Str1: This is another test string...
Str2: This is another test string...
呢?
测试答案是前者。
再看看片段2:
class Program{static void Main(string[] args){#region TestObjectObjectToTest ott1, ott2;//ott1 = ott2 = new ObjectToTest(100);ott2 = new ObjectToTest(100);ott1 = ott2;Console.WriteLine("OTT1: " + ott1.Num);Console.WriteLine("OTT2: " + ott2.Num);ott2 = new ObjectToTest(150);Console.WriteLine("OTT1: " + ott1.Num);Console.WriteLine("OTT2: " + ott2.Num); #endregionConsole.Read();}}class ObjectToTest{int num;public int Num{get { return num; }set { num = value; }}public ObjectToTest(int num){Num = num;}}
输出结果又是如何呢?这里的ott1和ott2都是对象,也就是涉及到引用传递的问题了。我们记new ObjectToTest(100)为obj1, new ObjectToTest(150)为obj2.则在语句ott1=ott2执行后,ott1是对ott2的引用,还是对obj1的引用呢?在后面当ott2=new ObjectToTest(150)执行后,ott1是对obj1的引用还是对obj2的引用呢?
执行代码,观看结果为:
OTT1: 100
OTT2: 100
OTT1: 100
OTT2: 150
可知,这里的ott1只是对obj1的引用,而非obj2的引用。
这篇关于关于var1=var2=something赋值语句的思考的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!