c# - 继承类属性中的属性差异

标签 c#

我有两个类:ElementDisplay

现在这两个类都有很多共同的属性,所以我考虑从一个基类继承。

问题来了。对于序列化,Element 类应该在每个属性之前有 [XmlIgnore],但 Display 类没有。

我该如何处理?

旧的:

public class Element
{
    [Browsable(false)]
    [XmlIgnore]
    public Brush BackgroundBrush { get; set }
}

public class Display
{
    public Brush BackgroundBrush { get; set }
}

新:

public class DispBase
{
    public Brush BackgroundBrush { get; set; }
}

public class Element : DispBase
{
    // what to write here, to achieve XmlIgnore and Browsable(false)?
}

public class Display : DispBase
{
}

最佳答案

您可以使基类和属性抽象化,并在需要时为每个派生类设置属性:

public abstract class DispBase
{
    public abstract Brush BackgroundBrush { get; set; }
}

public class Element : DispBase
{
    [XmlIgnore]
    [Browsable(false)]
    public override Brush BackgroundBrush { get; set; }
}

public class Display : DispBase
{
    public override Brush BackgroundBrush { get; set; }
}

关于c# - 继承类属性中的属性差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31243445/

相关文章:

c# - 如何在 C++ 中将整数转换为字节,以便 Unity 在通过 UDP 传输后可以理解它们

c# - 通过调用 <asyncmethod>.Result 实现同步方法

c# - 取消转义由 mvc 应用程序返回的转义 unpritable 编码字符串的简单方法

c# - 如何在 response.redirect 之前执行启动脚本?

c# - C# 中的 TreeView.Nodes[int].Name 在哪里?

c# - 下拉菜单始终处于事件状态并显示

c# - DataTable 不接受 MySQL 表中的 DateTime 字段

c# - C# 代码中的模式匹配 F# 类型

c# - 代码在相等比较时返回 false?

c# - 类型不匹配时如何使 ASP.NET Web API 反序列化失败