【发布时间】:2012-01-10 05:02:05
【问题描述】:
我目前正在为 HL7 消息构建对象模型。如果不深入研究,我们的基本结构类似于:
- 基础对象
- 中间对象
- DeepMessage1
- DeepMessage2
- 消息1
- 消息2
- 中间对象
我想要一个深拷贝/克隆,它将所有类似属性从 DeepMessage1 复制到 DeepMessage2 或 Message1 或 Message2。
public class BaseObject
{
PersonName Name; //A personName includes a first name and last name.
}
public class IntermediaryObject : BaseObject
{
Accident accident; //An accident codes and a description.
}
public class Message1 : BaseObject
{
//this class doesn't actually contain any special handling, just used for
//easy understanding for the API
}
public class Message2 : BaseObject
{
DateTime AdmissionDate; //Note the admission date is also contained in
//DeepMessage1, but not DeepMessage2
}
public class DeepMessage1 : IntermediaryObject
{
DateTime AdmissionDate; //Note this property is also contained in Message2 and
//needs to be copied
}
public class DeepMessage2 : IntermediaryObject
{
DateTime DischargeDate;
}
考虑到这种结构,我希望能够创建一个对象与另一个对象共享的每个属性的深层副本。 This other question 是一个非常好的开始,但最终我不能使用反射,因为那是浅克隆,并且序列化需要完全相同的对象。
我最终得到了这段代码,但它只执行了浅拷贝。
public T Copy<T>() where T : new()
{
T destination = new T();
if (destination is HL7Message)
{
foreach (var destinationProperty in destination.GetType().GetProperties())
{
foreach (var sourceProperty in this.GetType().GetProperties())
{
if (destinationProperty.Name.Equals(sourceProperty.Name))
{
destinationProperty.SetValue(destination, destinationProperty.GetValue(this, null), null);
}
}
}
return destination;
}
else
{
throw new InvalidOperationException("The destination copy type is not an HL7Message object");
}
}
我希望在我的if (destinationProperty.Name.Equals(sourceProperty.Name)) 块中,我可以尝试对特定基类型的任何属性(我的库中的所有对象都扩展)调用 Copy。但是,我无法让该部分中的 Copy 工作,因为我无法在运行时确定 T。
我是否只需要为特定对象创建一个单独的副本类型并让消息使用该副本,还是有一种方法可以做到这一点,这太疯狂了?
【问题讨论】:
-
如果您要复制的属性是 DateTime,则深复制/浅复制无关紧要 DateTime 是值类型,值的副本,因为没有对复制的引用。
标签: c# inheritance clone