我无法理解下面给出的两组代码片段的输出。怎么没有真正理解浅拷贝的概念。怎么解释?
班级:
public class Person : ICloneable
{
public string Name;
public int[] arr;
public object Clone()
{
return this.MemberwiseClone();
}
}
代码片段 1:
static void Main(string[] args)
{
Person p1 = new Person();
p1.Name = "Name1";
p1.arr = new int[5] {1,2,3,4,5 };
Person p2 = (Person)p1.Clone();
p1.Name = "Name2";
p1.arr[0] = 11;
Console.WriteLine(p2.Name);
Console.WriteLine(p2.arr[0].ToString());
Console.Read();
}
输出:名称1 11
怀疑:字符串不是引用类型。那么为什么 p2.Name 在片段 1 中打印为“Name1”
代码片段 2:
static void Main(string[] args)
{
Person p1 = new Person();
p1.Name = "Name1";
p1.arr = new int[5] { 1, 2, 3, 4, 5 };
Person p2 = (Person)p1.Clone();
p1.Name = "Name2";
p1.arr = new int[5] { 11, 12, 13, 14, 15 };
Console.WriteLine(p2.Name);
Console.WriteLine(p2.arr[0].ToString());
Console.Read();
}
输出:名称1 1