如果string是引用类型,为什么strA的值在这种情况下不会改变?

时间:2017-09-28 19:40:58

标签: c# .net pass-by-reference value-type reference-type

我以为我理解了Reference和Value类型之间的区别。我以为 'string'只保留值类型语义,同时保留引用类型的行为。然后我尝试了这个,期望在两种情况下看到True返回。 我误解了什么?

        string strA = "AAA";
        string strB = strA;
        strB = "BBB";
        Console.WriteLine($"strA is {strA} and strB is {strB}");
        Console.WriteLine($"The statement: strA == strA is {strA == strB} \n");

        Car car1 = new Car();
        car1.Horsepower = 190;
        Car car2 = car1;
        car2.Horsepower = 200;
        Console.WriteLine($"car1.Horsepower is {car1.Horsepower} and car2.Horsepower is {car2.Horsepower}");
        Console.WriteLine($"The statement: car1 == car2 is {car1 == car2}");

输出:

  

strA是AAA,strB是BBB

     

声明:strA == strA为假

     

car1.Horsepower是200而car2.Horsepower是200

     

声明:car1 == car2为True

1 个答案:

答案 0 :(得分:2)

字符串文字指定字符串实例。将字符串转换为汽车以方便,这基本上就是你用字符串做的事情:

Car AAA = new Car();
Car BBB = new Car();

Car carA = AAA;
Car carB = carA;
carB = BBB;
Console.WriteLine($"carA is {carA} and carB is {carB}");
Console.WriteLine($"The statement: carA == carB is {carA == carB}

最大的区别是你使用"string literals"而不是new Car / new String,因为编译器预先为静态字符串分配对象。