继承类属性中的属性差异

时间:2015-07-06 10:26:08

标签: c#

我有两个课程:DisplayElement

现在这两个类都有许多常见属性,所以我考虑从基类继承。

现在出现了问题。对于序列化,[XmlIgnore]类应该在每个属性之前有Display,但public class Element { [Browsable(false)] [XmlIgnore] public Brush BackgroundBrush { get; set } } public class Display { public Brush BackgroundBrush { get; set } } 类不应该。{/ p>

我该如何处理?

旧:

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
{
}

新:

{{1}}

2 个答案:

答案 0 :(得分:5)

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

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; }
}

答案 1 :(得分:1)

您可以使用XmlAttributes类并动态设置XmlIgnore。

示例类:

public class Brush { }

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

public class Element : DispBase { }
public class Display : DispBase { }

示例代码:

var element = new Element { BackgroundBrush = new Brush() };
var display = new Display { BackgroundBrush = new Brush() };

using (var fs = new FileStream("test1.txt", FileMode.Create))
{
    var attributes = new XmlAttributes { XmlIgnore = true };

    var overrides = new XmlAttributeOverrides();
    overrides.Add(typeof(DispBase), "BackgroundBrush", attributes);

    var ser = new XmlSerializer(typeof(Element), overrides);
    ser.Serialize(fs, element);
}

using (var fs = new FileStream("test2.txt", FileMode.Create))
{
    var ser = new XmlSerializer(typeof(Display));
    ser.Serialize(fs, display);
}