我有一个类似于以下示例的多级类层次结构:
Model Dto
/ \ / \
CompanyModels User Model, etc.. CompanyDto UserDto, etc..
/ \ / \
PeopleModel OfficeModel PeopleDto OfficeDto
所有“公司模式”共享相同的属性(名称,地址等)和子模型“人物”,“办公室”等...添加其他属性。
在“Model”基类中,我有以下方法,旨在将模型剥离到仅通过线路所需的内容:
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;
}
}
请帮助我弄清楚实现这一目标的正确模式是什么,因为目前我认为我刚刚盯着这个太久......
提前致谢!
答案 0 :(得分: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;
}
}