2011-05-18 90 views
1

为什么b.b不会像f.f一样变成“a2”?C#参考问题

谢谢。

public class Test 
{ 
    public static void Main() 
    { 
     Foo f = new Foo 
     { 
      f = getStr() 
     }; 

     Boo b = new Boo 
     { 
      b = f.f 
     }; 


     f.f = "a2"; 

     Console.WriteLine(f.f); 
     Console.WriteLine(b.b); 
    } 

    public static string getStr() 
    { 
     string a = "a1"; 
     return a; 
    } 
} 

public class Foo 
{ 
    public string f { get; set; } 
} 

public class Boo 
{ 
    public string b { get; set; } 
} 

回答

1

.NET中的字符串是不可变的,也就是说,您不是发送引用,而是发送值。

在.NET中的其他类中,您正在传递引用。就像这样:

Car c = new Car(); 
c.Name = "Ford"; 
var d = c; 
d.Name = "Volvo"; 
c.Name; //Volvo 

但字符串,它是这样工作:

string s = "Hey"; 
string c = s; 
c = "World!"; 
//s is still "Hey" 

看这个问题的详细资料:Why .NET String is immutable?

它,当然,与其他相同类。

Car c = new Car(); 
c.Name = "Ford"; 
Car d = c; 
//d.Name == "Ford"; 
d = new Car(); 
d.Name = "Volvo"; 
//c.Name is still "Ford" 
1

Boo.bFoo.f是字符串,而不是指向字符串。
指定Foo.fBoo.bFoo.f的值赋值为Boo.b。在完成任务后,他们是独立的。更改Foo.f不会更改Boo.b

+0

实际上Boo.b和Foo.F_are_引用(指针)到字符串。 – 2011-05-18 09:25:48

+0

不在OP的意思,这就是为什么我没有使用该单词,而是单词“指针”,而不是。 – 2011-05-18 09:30:08

0

为什么呢?你没有改变它。仅仅因为你在过去将b.b设置为f.f,并不意味着它会随着任何更改而继续进行。

您设置了一个值,而不是引用。

3

这里有一个简单的代码演示了什么我想你期待看到:

string x = "hello"; 
string y = x; 
x = "there"; 

你似乎期待y"there"在这一点上。但是xy是完全独立的变量 - 秒中的赋值仅将x(对字符串“hello”的引用)的值复制到y。第三行将不同的值分配给x(对字符串“there”的引用) - 它不会更改y的值,该值仍然是字符串“hello”的对象。

您的示例更复杂,因为它使用具有自动实现属性的单独类型 - 但基本概念相同。