[英]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
类, BaseDto
和DerivedDto
将通过另一个类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.