淺拷貝的一個Demo
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Car
{
public string name;
public Car(string name)
{
this.name=name;
}
}
class Person
{
public int id;
public string name;
public Car car;
public Person(int id, string name,Car car)
{
this.id = id;
this.name = name;
this.car = car;
}
public Object Clone() //對外提供一個創建自身的淺表副本的能力
{
return this.MemberwiseClone();
}
}
public class TestClone
{
public static void Main()
{
Person p1 = new Person(1, "Scott",new Car("寶馬"));
Person p2 = (Person)p1.Clone(); //克隆一個對象
Console.WriteLine("改變P1的值");
p1.id = 2;
p1.name="Lacy";
p1.car.name="紅旗";
Console.WriteLine("P1:id={0}----------->name={1}------>car={2}", p1.id,p1.name,p1.car.name);
Console.WriteLine("P2:id={0}----------->name={1}------>car={2}", p2.id, p2.name,p2.car.name);
}
}
}