模式帮助:C#中的多级泛型继承

本文关键字:多级 泛型 继承 帮助 模式 | 更新日期: 2023-09-27 18:27:10

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

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

All "Company Models" share the same properties (Name, address, etc...) and the child models "People", "Office", etc... add additional properties.

In the "Model" base class, I have the following method, intended to strip the models down to only what is necessary to pass across the wire:

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"answers"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;
     }
}

请帮我弄清楚实现这一目标的正确模式是什么,因为目前我认为我已经盯着这个看太久了。。。

提前感谢!

模式帮助:C#中的多级泛型继承

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;
    }
}