gpt4 book ai didi

c# - MemberwiseClone 与新对象

转载 作者:行者123 更新时间:2023-11-30 16:59:39 26 4
gpt4 key购买 nike

我得到了:

internal sealed class A : ICloneable
{
public Collection<B> CollectionB { get; set; }

public int Int1 { get; set; }
public int Int2 { get; set; }
public int Int3 { get; set; }
public int Int4 { get; set; }
//. . .
//some different value types, lets think all of type int for simplyfy

public object Clone()
{
//Need to implement Clone
}

}


internal sealed class B : ICloneable
{
public Collection<Bitmap> SomeBitmaps { get; set; }

public int Int1 { get; set; }
public int Int2 { get; set; }
//. . .
//etc.

public object Clone()
{
//same as class A
}
}

我应该如何在此对象中实现 Clone()?我需要进行深度克隆,因为我需要将此对象作为不同任务中的 DTO。

我应该让它像(对于 A):

public object Clone()
{
var clone = this.MemberwiseClone();
var cloneCollectionB = new Collection<B>();
foreach(var element in CollectionB)
{
cloneCollectionB.Add(((B)element).Clone());
}
((A)clone).CollectionB = cloneCollectionB;
return clone;
}

对于 B 同样的方式,或者有不同的好的模式/解决方案?我应该使用 new object() 而不是 MemberwiseClone() 并手动设置字段吗?谢谢。

最佳答案

你可以这样做:

internal sealed class A: ICloneable {
// Let it be List, OK?
// It looks, that you don't need "set" here
public List<B> CollectionB { get; }

public int Int1 { get; set; }
public int Int2 { get; set; }
public int Int3 { get; set; }
public int Int4 { get; set; }

// It's more convenient to return A, not Object
// That's why explicit interface implementation
Object ICloneable.Clone() {
return this.Clone();
}

public A Clone() {
A result = new A();

result.Int1 = Int1;
result.Int2 = Int2;
result.Int3 = Int3;
result.Int4 = Int4;

// Deep copy: you have to clone each B instance:
foreach(B item in CollectionB)
result.CollectionB.Add(item.Clone()); // <- thanks for explicit inteface impl. it ret B

return result;
}
}

internal sealed class B: ICloneable {
// Let it be List
// It looks, that you don't need "set" here
public List<Bitmap> SomeBitmaps { get; }

public int Int1 { get; set; }
public int Int2 { get; set; }
//. . .
//etc.

// It's more convenient to return B, not Object
// That's why explicit interface implementation
Object ICloneable.Clone() {
return this.Clone();
}

// It's more convenient to return B, not Object
public B Clone() {
B result = new B();

result.Int1 = Int1;
result.Int2 = Int2;
// ...
//etc.

// Deep copy: you have to create new bitmaps here
foreach(Bitmap source in SomeBitmaps)
result.SomeBitmaps.Add(new Bitmap(source));

return result;
}
}

关于c# - MemberwiseClone 与新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23515457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com