我有一泛型变量A,赋给另一个泛型变量B后,发现A的值会跟着B的改变而改变,不知何因,请高手解释一下!如下面的代码:
private void button1_Click(object sender, EventArgs e)
{
List<string> A=new List<string>();
A.Add("123"); Test(A);
Console.WriteLine(A.Count);
}
private void Test(List<string> a)
{
List<string> B = new List<string>();
B = a;
B.Add("321");
}
执行到"Console.WriteLine(A.Count);"时,输出值会是2,怎么想都想不明白!
private void button1_Click(object sender, EventArgs e)
{
List<string> A=new List<string>();
A.Add("123"); Test(A);
Console.WriteLine(A.Count);
}
private void Test(List<string> a)
{
List<string> B = new List<string>();
B = a;
B.Add("321");
}
执行到"Console.WriteLine(A.Count);"时,输出值会是2,怎么想都想不明白!
B = a;==>
b = a其实就是将B变量指向了a对象.
B = a;<==> List<string> B = a;
{
List<string> B = new List<string>(a);
B.Add("321");
}
{
List<string> B = new List<string>(a);
B.Add("321");
}