访问基类C#中的隐藏属性 [英] Access hidden property in base class c#
问题描述
在我的ASP.NET Core API中,我有一个DTO类BaseDto
和另一个从BaseDto
继承并隐藏其某些属性的DerivedDto
,因为在DerivedDto
中是必需的.我还有一个BaseModel
类,BaseDto
和DerivedDto
都将通过另一个类Mapper
映射到该类.
类似于以下代码:
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
};
}
但是事实证明,将DerivedDto
对象传递给MapToModel
方法时,它试图访问BaseDto
(它们是null
)的值,而不是DerivedDto
的值.>
有什么办法可以实现这种行为?
我只能考虑将BaseDto
声明为抽象,但这会阻止我实例化它,这是我需要做的.
您需要将BaseDto类属性声明为虚拟属性,然后在DerivedDto类中重写它,如下所示:
public class BaseDto
{
public virtual string Name { get; set; }
}
public class DerivedDto : BaseDto
{
public override string Name { get; set; }
}
另外,请修复您的Mapper类方法. BaseModel中没有属性Name.它必须是"NameModel = dto.Name"
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"
这篇关于访问基类C#中的隐藏属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!