0

我有一个类似于以下示例的多级类层次结构:

                  Model                                      Dto
                 /    \                                     /  \
     CompanyModels    User Model, etc..           CompanyDto   UserDto, etc..
     /         \                                  /        \
PeopleModel  OfficeModel                     PeopleDto   OfficeDto

所有“公司模型”共享相同的属性(姓名、地址等),子模型“人员”、“办公室”等...添加其他属性。

在“模型”基类中,我有以下方法,旨在将模型剥离到只需要通过电线传递的内容:

public virtual T AsDto<T>() where T : Dto, new()
{
     var dto = new T();

     dto.CreatedDate = this.CreatedDate;
     dto.CreatedUserID = this.CreatedUserID; //etc..

     return dto;
} 

在我的一生中,我无法找出允许“CompanyModel”处理“PeopleModel”和“OfficeModel”共享的属性分配的最佳模式。

目前我有以下设置,我相当肯定不会工作:

public class CompanyModel : Model
{
     public override CompanyDto AsDto<T>()
     {
          CompanyDto c = base.AsDto<CompanyDto>();
          c.CompanyName = this.CompanyName; //etc...
          return c;
     }
}

public class PeopleModel : CompanyModel
{
     public override PeopleDto AsDto<T>()
     {
          PeopleDto p = base.AsDto<PeopleDto>() as PeopleDto; //will return null
          p.FirstName = this.FirstName;
          p.LastName = this.LastName; //etc...
          return p;
     }
}

请帮助我弄清楚完成此操作的正确模式是什么,因为目前我认为我已经盯着这个太久了......

提前致谢!

4

1 回答 1

0
public class Model
{
    public DateTime CreatedDate { get; set; }
    public int CreatedUserID { get; set; }

    public virtual Dto AsDto()
    {
        return FillDto(new Dto());
    }

    protected Dto FillDto(Dto dto)
    {
        dto.CreatedDate = this.CreatedDate;
        dto.CreatedUserID = this.CreatedUserID; //etc..
        return dto;
    }
}


public class CompanyModel : Model
{
    public string CompanyName { get; set; }

    public override Dto AsDto()
    {
        return FillDto(new CompanyDto());
    }

    protected CompanyDto FillDto(CompanyDto dto)
    {
        base.FillDto(dto);
        dto.CompanyName = this.CompanyName;
        return dto;
    }
}

public class PeopleModel : CompanyModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public override Dto AsDto()
    {
        return FillDto(new PeopleDto());
    }

    protected PeopleDto FillDto(PeopleDto dto)
    {
        base.FillDto(dto);
        dto.FirstName = this.FirstName;
        dto.LastName = this.LastName; //etc...
        return dto;
    }
}
于 2013-08-11T23:15:32.783 回答