代码如下:
object obj = new object();
ArrayList list = new ArrayList();
while(...)
{
.....对obj操作的代码
list.add(obj);
}
list中添加是obj的引用如何将每次添加的obj复制一份添加到list中呢。现在的效果是所有的obj都变成了最后add的那个obj
object obj = new object();
ArrayList list = new ArrayList();
while(...)
{
.....对obj操作的代码
list.add(obj);
}
list中添加是obj的引用如何将每次添加的obj复制一份添加到list中呢。现在的效果是所有的obj都变成了最后add的那个obj
把这个初始化放到while循环里while(...)
{
object obj = new object();
.....对obj操作的代码
list.add(obj);
}
那你自己写一个复制的Clone方法帮助实现吧。SqlHelper里面有一段是自己写了一个拷贝SqlParameter的代码,可以找到参考一下。
你错了.ICloneable接口可以做深拷贝也可以搞浅拷贝,
具体要看你的object是怎么个实现
{ static void Main(string[] args)
{
A a = new A();
a.b.Str = "1"; A newA = (A)a.Clone();
newA.b.Str = "2"; Console.WriteLine(a.b.Str);
Console.WriteLine(newA.b.Str); Console.ReadKey();
} } public class A : ICloneable
{
public B b = new B();
public object Clone()
{
A a = new A();
return a;
}
} public class B
{
private string _str = string.Empty;
public string Str
{
get
{
return _str;
}
set
{
_str = value;
}
}
}
object o = new object();
ArrayList list = new ArrayList(); for (int i = 0; i < 5; i++)
{
o = i;
list.Add(o);
} for (int i = 0; i < list.Count; i++)
Console.WriteLine(list[i].ToString());
NEW一下那里会不对呢? while(...)
{
object obj = new object();
.....对obj操作的代码 //这里是你操作obj的代码.
list.add(obj);
} 每次new一个object对象,在堆里为obj分配内存地址.你之前的错误就是在内存中只分配了一次内存地址,之后的操作是反复的在这个内存地址写数据.
DataTable dt = new DataTable();
DataTable tdt = dt.copy();
{ static void Main(string[] args)
{
object o = new object();
ArrayList list = new ArrayList();
A a = new A();
for (int i = 0; i < 5; i++)
{
A newA = (A)a.Clone();
newA.b.Str = i.ToString();
o = newA;
//a.b.Str = i.ToString();//这两行代码去掉注释,把前行前的三段注释掉可以对比一下结果
//o = a;
list.Add(o);
} for (int i = 0; i < list.Count; i++)
Console.WriteLine((((A)list[i]).b.Str)); Console.ReadKey();
} } public class A : ICloneable
{
public B b = new B();
public object Clone()
{
A a = new A();
return a;
}
} public class B
{
private string _str = string.Empty;
public string Str
{
get
{
return _str;
}
set
{
_str = value;
}
}
}
{
public B b = new B();
public object Clone()
{
A a = new A();
return a;
}
}
克隆和直接new一个对象,有区别吗?
看看下例,看看有区别吗?
public class Program
{
static void Main(string[] args)
{
A a = new A();
a.str = "1";
A _a = (A)a.Clone();
a.str = "2";
Console.WriteLine(_a.str);
Console.WriteLine(a.str);
Console.ReadKey();
} } public class A : ICloneable
{
public string str = string.Empty;
public object Clone()
{
A a = new A();
a.str = str;
return a;
}
}