对于集合类,可以这么写。using System; using System.Collections.Generic; using System.Text;class Program { static void Main(string[] args) { List<int> a = new List<int>(); a.Add(100); List<int> b = new List<int>(a); b[0] = 0; Console.WriteLine("{0}\n{1}", a[0], b[0]); Console.Read(); } }
对于自定义类,可以用 MemberwiseClone() 方法,微软内部代码也经常这么做。using System; using System.Collections.Generic; using System.Text;class A { public int i = 5; public A ValueCopy() { object o=this.MemberwiseClone(); return (A)o; } }class Program { static void Main(string[] args) { A a1 = new A(); // 这句调用 MemberwiseClone 进行了值 copy // 可以用 A a2 = a1; 替换比较结果 A a2 = a1.ValueCopy();
当然,最好还是在设计的时候解决。using System; using System.Collections.Generic; using System.Text;// 当然最简单的方法还是把 class 换成 struct // 功能和类基本上都一样,struct 却是值类型的 struct A { public int i; }class Program { static void Main(string[] args) { A a1 = new A(); a1.i = 5; A a2 = a1; a2.i = 10; Console.WriteLine("{0}\n{1}", a1.i, a2.i); Console.Read(); } }有些类支持序列化,也能完成类的值拷贝。 还有一种反射的方法,也可以做到类的值拷贝,很复杂,不说了。
using System.Collections.Generic;
using System.Text;class Program
{
static void Main(string[] args)
{
List<int> a = new List<int>();
a.Add(100);
List<int> b = new List<int>(a);
b[0] = 0;
Console.WriteLine("{0}\n{1}", a[0], b[0]);
Console.Read();
}
}
using System.Collections.Generic;
using System.Text;class A
{
public int i = 5;
public A ValueCopy()
{
object o=this.MemberwiseClone();
return (A)o;
}
}class Program
{
static void Main(string[] args)
{
A a1 = new A(); // 这句调用 MemberwiseClone 进行了值 copy
// 可以用 A a2 = a1; 替换比较结果
A a2 = a1.ValueCopy();
a2.i = 10;
Console.WriteLine("{0}\n{1}", a1.i, a2.i);
Console.Read();
}
}
using System.Collections.Generic;
using System.Text;// 当然最简单的方法还是把 class 换成 struct
// 功能和类基本上都一样,struct 却是值类型的
struct A
{
public int i;
}class Program
{
static void Main(string[] args)
{
A a1 = new A();
a1.i = 5;
A a2 = a1;
a2.i = 10;
Console.WriteLine("{0}\n{1}", a1.i, a2.i);
Console.Read();
}
}有些类支持序列化,也能完成类的值拷贝。
还有一种反射的方法,也可以做到类的值拷贝,很复杂,不说了。