//浅拷贝的实现
//2004.9.2
using System;
class RefType {
public String name;
public Int32 age;
public RefType(String name,Int32 age)
{
this.name = name;
this.age = age;
}
}
//类型MyType实现了ICloneable接口,可以被浅拷贝
class MyType : ICloneable {
public RefType r; //引用类型字段
public String name; //值类型字段
public Int32 age; //值类型字段
public MyType(String name,Int32 age) {
this.name = name;
this.age = age;
r = new RefType(name,age);
}
public Object Clone() {
return MemberwiseClone();
}
}
//启动类
class App {
static void Main() {
MyType m1 = new MyType("张三",18);
MyType m2 = (MyType)m1.Clone();
Console.WriteLine(m2.name.ToString()+","+m2.age.ToString());
Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString());
m1.name = "李四";
m1.age = 19;
m1.r.name = "李四";
m1.r.age = 19;
Console.WriteLine(m2.name.ToString()+","+m2.age.ToString()); //值类型字段值没有改变
Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString()); //引用类型字段值改变了
}
}
//2004.9.2
using System;
class RefType {
public String name;
public Int32 age;
public RefType(String name,Int32 age)
{
this.name = name;
this.age = age;
}
}
//类型MyType实现了ICloneable接口,可以被浅拷贝
class MyType : ICloneable {
public RefType r; //引用类型字段
public String name; //值类型字段
public Int32 age; //值类型字段
public MyType(String name,Int32 age) {
this.name = name;
this.age = age;
r = new RefType(name,age);
}
public Object Clone() {
return MemberwiseClone();
}
}
//启动类
class App {
static void Main() {
MyType m1 = new MyType("张三",18);
MyType m2 = (MyType)m1.Clone();
Console.WriteLine(m2.name.ToString()+","+m2.age.ToString());
Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString());
m1.name = "李四";
m1.age = 19;
m1.r.name = "李四";
m1.r.age = 19;
Console.WriteLine(m2.name.ToString()+","+m2.age.ToString()); //值类型字段值没有改变
Console.WriteLine(m2.r.name.ToString()+","+m2.r.age.ToString()); //引用类型字段值改变了
}
}