访问基类C#中的隐藏属性 [英] Access hidden property in base class c#

查看:108
本文介绍了访问基类C#中的隐藏属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的ASP.NET Core API中,我有一个DTO类BaseDto和另一个从BaseDto继承并隐藏其某些属性的DerivedDto,因为在DerivedDto中是必需的.我还有一个BaseModel类,BaseDtoDerivedDto都将通过另一个类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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆