简体   繁体   中英

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 . 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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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