问题
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