gpt4 book ai didi

c# - 将 parent 转换为 child

转载 作者:太空宇宙 更新时间:2023-11-03 19:27:45 25 4
gpt4 key购买 nike

我有数十个域对象(用户、组、角色、社区、帖子等)。我还有扩展对象(UserExt、GroupExt 等),它们从这些对象派生并包含一些附加数据。在我的数据访问控制层中,有用于检索基础对象的方法。当我需要用数据填充子对象时,我会使用这些方法,但每次我都需要将该结果转换为子类型时。
由于我不能将父对象转换为子对象,我需要为每个父子对提供转换器(通过构造函数、方法、对现有转换器的扩展或任何其他方式)。这就是我不喜欢的,因为如果我向基类型添加任何字段我可能会忘记调整我的转换器。是否有更自动化的方法来从父项填充子项的字段?
谢谢!

附言:代码:

域对象:

public class Role : OutdoorObject
{
public String Name { get; set; }
public Int32 CreatedById { get; set; }
public Int32 UpdatedById { get; set; }
}

public class RoleExt : Role
{
public IPrincipal CreatedBy { get; set; }
public IPrincipal UpdatedBy { get; set; }
}

数据访问层:

public Role GetById(Int32 roleId)
{
try
{
// seek in cache, return if found
LQ_Role lqRole = context.LQ_Roles.FirstOrDefault(r => r.RoleID == roleId);
Role result = LQMapper.LQToObject(lqRole);
// put result to cache
return result;
}
catch (Exception ex)
{
if (ex is BaseRepositoryException) throw ex;
else throw new UnknownRepositoryException(ex.Message);
}
}

服务层:

    public Role GetById(IPrincipal Executer, int roleID)
{
try
{
// perform operation
Role r = _repo.GetById(roleID);

// check access
if (!CanRead(Executer, r)) throw new OperationIsNotPermittedServiceException();

return r;
}
catch (Exception ex)
{
// ...
}
}

public RoleExt GetExtById(IPrincipal Executer, int roleID)
{
try
{
// perform operation
Role r = GetById(IPrincipal Executer, int roleID);
RoleExt result = new RoleExt();
// here i need to convert r to result
// and populate addition fields
result.CreatedBy = userService.GetById(Executer, r.CreatedById);
result.UpdatedBy = userService.GetById(Executer, r.UpdatedById);

// check access
if (!CanRead(Executer, result)) throw new OperationIsNotPermittedServiceException();

return result;
}
catch (Exception ex)
{
//...
}
}

最佳答案

使用反射,这会将所有公共(public)属性从父级复制到子级:

  public static void CopyOver(Parent p, Child c)
{
PropertyInfo[] props = p.GetType().GetProperties(BindingFlags.Public);

foreach( PropertyInfo pi in props)
{
pi.SetValue( c, pi.GetValue( p) );
}
}

关于c# - 将 parent 转换为 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7326030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com