Access hidden property in base class c#

帅比萌擦擦* 提交于 2020-01-24 14:09:13

问题


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. I also have a BaseModel class to which both BaseDto and DerivedDto will be mapped through another class 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.

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.


回答1:


You need to declare your BaseDto class property as virtual and then override it in the DerivedDto class as follows:

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. There is no property Name in the BaseModel. It needs to be "NameModel = dto.Name"



来源:https://stackoverflow.com/questions/59840471/access-hidden-property-in-base-class-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!