问题描述
我正在使用第三方的一组Web服务,但遇到了一个小障碍.在手动制作将每个属性从源复制到目标的方法之前,我想我想在这里寻求更好的解决方案.
I'm using a 3rd party's set of webservices, and I've hit a small snag. Before I manually make a method copying each property from the source to the destination, I thought I'd ask here for a better solution.
我有2个对象,一个是Customer.CustomerParty类型,一个是Appointment.CustomerParty类型. CustomerParty对象实际上是属性,并且子对象完全相同.但是我不能从1投射到另一个.
I've got 2 objects, one of type Customer.CustomerParty and one of type Appointment.CustomerParty. The CustomerParty objects are actually property and sub-oject exactly the same. But I can't cast from 1 to the other.
因此,我需要从Web服务中找到某个人.我可以通过调用Customer.FindCustomer(customerID)来实现,它返回一个Customer.CustomerParty对象.
So, I need to find a certain person from the webservice. I can do that by calling Customer.FindCustomer(customerID) and it returns a Customer.CustomerParty object.
我需要带走我找到的那个人,然后在"CreateAppointment"请求中向下使用几行. Appointment.CreateAppointment需要一个约会对象,并且约会对象包含一个CustomerParty对象.
I need to take that person that I found and then use them a few lines down in a "CreateAppointment" request. Appointment.CreateAppointment takes an appointment object, and the appointment object contains a CustomerParty object.
但是,它想要的CustomerParty对象实际上是Appointment.CustomerParty.我有一个Customer.CustomerParty.
However, the CustomerParty object it wants is really Appointment.CustomerParty. I've got a Customer.CustomerParty.
明白我的意思吗?有什么建议吗?
See what I mean? Any suggestions?
推荐答案
在编写域模式时,这种情况很常见.本质上,您需要在两个对象之间编写一个域转换器.您可以通过几种方法执行此操作,但是我建议在目标类型中使用一个覆盖的构造函数(或静态方法),该构造函数接受服务类型并执行映射.由于它们是两种CLR类型,因此您不能直接从一种转换为另一种.您需要逐成员复制.
This scenario is common when writing domain patterns. You essentially need to write a domain translator between the two objects. You can do this several ways, but I recommend having an overridden constructor (or a static method) in the target type that takes the service type and performs the mapping. Since they are two CLR types, you cannot directly cast from one to the other. You need to copy member-by-member.
public class ClientType
{
public string FieldOne { get; set; }
public string FieldTwo { get; set; }
public ClientType()
{
}
public ClientType( ServiceType serviceType )
{
this.FieldOne = serviceType.FieldOne;
this.FieldTwo = serviceType.FieldTwo;
}
}
或
public static class DomainTranslator
{
public static ServiceType Translate( ClientType type )
{
return new ServiceType { FieldOne = type.FieldOne, FieldTwo = type.FieldTwo };
}
}
这篇关于2个对象,完全相同(名称空间除外)c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!