【问题标题】:Access hidden property through base class c#通过基类c#访问隐藏属性
【发布时间】:2020-01-21 14:47:42
【问题描述】:

在我的 ASP.NET Core API 中,我有一个 DTO 类 BaseBDto 和另一个继承自它的 DerivedBDto,并隐藏了它的一些属性,因为它们在 DerivedBDto 中是必需的。 BaseBDtoDerivedBDto 的属性是另一个类的对象,分别是 BaseADtoDerivedADto,它们遵循与第一个类相同的逻辑。我还有一个 BaseModel 类,BaseBDtoDerivedBDto 都将通过另一个类 Mapper 映射到该类。

类似于以下代码:

using System.ComponentModel.DataAnnotations;

public class BaseADto
{
    public string Name { get; set; }
}

public class DerivedADto : BaseADto
{
    [Required]
    public new string Name { get; set; }
}

public class BaseBDto
{
    public BaseADto A { get; set; }
}

public class DerivedBDto : BaseBDto
{
    [Required]
    public new DerivedADto A { get; set; }
}

public class BaseModel
{
    public string NameModel { get; set; }
}

public static class Mapper
{
    public static BaseModel MapToModel(BaseBDto dto) => new BaseModel
    {
        NameModel = dto.A.Name
    };
}

但事实证明,当将DerivedBDto 对象传递给MapToModel 方法时,它试图访问BaseBDto(即null)的值,而不是DerivedBDto 的值。

有什么方法可以实现这种行为吗?

我只能考虑将BaseBDto 声明为抽象,但这会阻止我实例化它,我需要这样做。

PS:我已经问过类似的问题here,但我过度简化了我的代码示例,所以我觉得有必要再问一个问题。 此外,那里提供的解决方案不起作用,因为我不能用 DerivedADto 覆盖 DerivedBDto 的 A 属性,因为它必须与 BaseBDto 的 A 属性具有相同的类型。

【问题讨论】:

  • 正如您在其他问题中的答案所建议的那样,您需要使用虚拟和覆盖。隐藏属性仅在没有任何东西将其作为基类访问时才有效,但如果您将对象作为基类传递,它将使用隐藏属性而不是隐藏属性。 Virtual 和 Override 是您想要解决的问题。
  • 这能回答你的问题吗? Access hidden property in base class c#
  • 以后,请考虑编辑您现有的问题。无需创建副本。
  • @Tarazed 我不认为这个问题与我原来的问题重复。就像我说的,我在另一个问题中过度简化了我的代码示例。此外,该解决方案在这种特殊情况下不起作用,因为我无法使用从原始属性类型派生的类型覆盖属性。请参阅 this 并取消注释 virtualoverride 关键字以切换编译错误。
  • 如果您的返回类型不同,您不应该隐藏任何内容,您应该考虑使用不同的名称。在这一点上,它是一个完全不同的功能。

标签: c# inheritance polymorphism


【解决方案1】:

您是否尝试过将MapToModel 签名更改为通用签名。下面

public static BaseModel MapToModel<T>(T dto) where T : BaseBDto => new BaseModel
{
    NameModel = dto.A.Name
};

【讨论】:

  • 这会产生与我的 MapToModel 方法版本相同的行为。
猜你喜欢
  • 1970-01-01
  • 2012-07-01
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多