日期:2014-05-19  浏览次数:20952 次

如何创建两个一模一样的对象,但不是引用
如ListBox   l1     =   new   ListBox();
l1.Top   =   50;

现在我想创建一个对象l2   l2的设置和l1一模一样,但修改了l2的值不会修改了l1的值

------解决方案--------------------
ListBox l2 = new ListBox();
l2.Top = 50;
其实你应该描述的更清楚些

------解决方案--------------------
你说的是克隆,你需要自己继承ICloneable(好像写错了,你自己查吧)接口,自己写吧,
------解决方案--------------------
l2 =l1.Clone();
------解决方案--------------------
用反射可以吧?
------解决方案--------------------
l2 =l1.Clone();

------解决方案--------------------
Clone的话要自己实现ICloneable,还有一种方法:
考虑用BinaryFormatter,将ListBox的实例序列化到MemoryStream中,然后再反序列化出另一个一模一样的实例:)
MemoryStream ms = new MemoryStream();
formmater.Serialize(ms,l1);
ListBox l2 = formmater.Deserialize(ms);
------解决方案--------------------
对象克隆有两种:深拷贝和浅拷贝
用序列化(BinaryFormatter)可以实现深拷贝...
------解决方案--------------------
happyhippy 的方法是可行的。不过lz真的确定要克隆一个对象?不是任何对象都可以克隆的。
------解决方案--------------------
framework中提供的对象有些不提供Clone的,可以从ComboBox等类中继承一下,在继承类中实现自定义的Clone函数,然后两个ComboBox的子类就可以直接Clone了,使用上感觉和Combobox没什么不一样
------解决方案--------------------
序列化是好办法
------解决方案--------------------
//类定义,像一般的类一样可以有方法,属性,事件,对象。
public class pChart
{
public Object crtObj;
public ChartType crtType;
public DataSet crtDataSet;
public string crtTitle = " ";
public int crtMinNumber = 0;
public int crtMaxNumber = 0;
public int crtScale = 0;
public string crtUnit = " ";

public pChart(string chartTitle,Object chartObject, ChartType chartType, DataSet chartDataSet, int minNumber, int maxNumber, int scale,string unit)
{
crtObj = chartObject;
crtType = chartType;
crtDataSet = chartDataSet;
crtTitle = chartTitle;
crtMinNumber = minNumber;
crtMaxNumber = maxNumber;
crtScale = scale;
crtUnit = unit;
}

}

//集合类,为之前的类提供add,remove方法。
public class AChart : System.Collections.CollectionBase
{

public AChart()
{ }
public void AddChart(string chartTitle, Object chartObject, ChartType chartType, DataSet chartDataSet, int minNumber, int maxNumber, int scale,string unit)
{
List.Add(new pChart(chartTitle,chartObject,chartType,chartDataSet,minNumber,maxNumber,scale,unit));
}
public void RemoveChart(int index)
{
if (index > Count - 1 || index < 0)
{
MessageBox.Show( "Index not valid! ");
}
else
{
List.RemoveAt(index);
}

}

public AChart Item
{
get
{
return this;
}
}
[System.Runtime.CompilerServices.IndexerName( "item ")]