2个对象,完全相同(命名空间除外)c#

Mat*_*att 15 c# casting namespaces

我正在使用第三方的网络服务,我遇到了一个小麻烦.在我手动创建一个方法将每个属性从源复制到目标之前,我想我会在这里要求更好的解决方案.

我有两个对象,一个是Customer.CustomerParty,另一个是Appointment.CustomerParty.CustomerParty对象实际上是属性和子对象完全相同.但是我无法从1投射到另一个.

所以,我需要从网络服务中找到某个人.我可以通过调用Customer.FindCustomer(customerID)来做到这一点,它返回一个Customer.CustomerParty对象.

我需要接受我找到的那个人,然后在"CreateAppointment"请求中使用它们几行.Appointment.CreateAppointment接受约会对象,约会对象包含CustomerParty对象.

但是,它想要的CustomerParty对象实际上是Appointment.CustomerParty.我有一个Customer.CustomerParty.

明白了吗?有什么建议?

djd*_*d87 12

你为什么不使用AutoMapper?然后你可以这样做:

TheirCustomerPartyClass source = WebService.ItsPartyTime();

YourCustomerPartyClass converted = 
    Mapper.Map<TheirCustomerPartyClass, YourCustomerPartyClass>(source);

TheirCustomerPartyClass original = 
    Mapper.Map<YourCustomerPartyClass, TheirCustomerPartyClass>(converted);
Run Code Online (Sandbox Code Playgroud)

只要属性相同,您就可以创建一个非常简单的地图,如下所示:

Mapper.CreateMap<TheirCustomerPartyClass, YourCustomerPartyClass>();
Mapper.CreateMap<YourCustomerPartyClass, TheirCustomerPartyClass>();
Run Code Online (Sandbox Code Playgroud)


Jor*_*mer 9

编写域模式时,这种情况很常见.您基本上需要在两个对象之间编写域转换器.您可以通过多种方式执行此操作,但我建议在目标类型中使用重写的构造函数(或静态方法)来获取服务类型并执行映射.由于它们是两种CLR类型,因此您无法直接从一种类型转换为另一种类型.您需要逐个成员复制.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

public static class DomainTranslator
{
    public static ServiceType Translate( ClientType type )
    {
        return new ServiceType { FieldOne = type.FieldOne, FieldTwo = type.FieldTwo };
    }
}
Run Code Online (Sandbox Code Playgroud)