简体   繁体   English

访问基类 c# 中的隐藏属性

[英]Access hidden property in base class c#

In my ASP.NET Core API, I have a DTO class BaseDto and another DerivedDto that inherits from BaseDto and hides some of its properties, because they're required in DerivedDto .在我的ASP.NET核心API,我有一个DTO类BaseDto和另一DerivedDto从继承BaseDto和隐藏了一些它的属性,因为他们在需要DerivedDto I also have a BaseModel class to which both BaseDto and DerivedDto will be mapped through another class Mapper .我还有一个BaseModel类, BaseDtoDerivedDto将通过另一个类Mapper映射到该类。

Something like the following code:类似于以下代码:

using System.ComponentModel.DataAnnotations;

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

public class DerivedDto : BaseDto
{
    [Required]
    public new string Name { get; set; }
}

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

public static class Mapper
{

    public static BaseModel MapToModel(BaseDto dto) => new BaseModel
    {
        NameModel = dto.Name
    };
}

But it turns out, when passing a DerivedDto object to the MapToModel method, it's trying to access the values of the BaseDto (which are null ) instead of the DerivedDto ones.但事实证明,当将DerivedDto对象传递给MapToModel方法时,它试图访问BaseDto的值(为null )而不是DerivedDto的值。

Is there any way I can achieve this behavior?有什么办法可以实现这种行为吗?

I can only think of declaring BaseDto as abstract, but that would prevent me from instantiating it, which I need to do.我只能想到将BaseDto声明为抽象的,但这会阻止我实例化它,而我需要这样做。

You need to declare your BaseDto class property as virtual and then override it in the DerivedDto class as follows:您需要将 BaseDto 类属性声明为 virtual ,然后在 DerivedDto 类中覆盖它,如下所示:

public class BaseDto
{
    public virtual string Name { get; set; }
}

public class DerivedDto : BaseDto
{
    public override string Name { get; set; }
}

Also, please fix your Mapper class method.另外,请修复您的 Mapper 类方法。 There is no property Name in the BaseModel. BaseModel 中没有属性 Name。 It needs to be "NameModel = dto.Name"它需要是“NameModel = dto.Name”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM