XmlElement继承

时间:2015-02-03 19:13:54

标签: c# xml inheritance

我想知道是否可以从XmlElement字段继承,例如

public class A{
          [XmlElement(ElementName = "Something", Form = XmlSchemaForm.Unqualified)]
        public string Something{ get; set; }
}

public class B: A
{
}

在使用B类对象时,我是否可以使用Something XmlElement字段进行操作,例如尝试解析以制作Int32?

谢谢

// EDITS

这是我在其他类中使用此xml元素字段所做的事情。

public class B: A, INotifyPropertyChanged
{
         public Int32? TimerValueFromApi
        {
            get 
            { 
                int timerValueFromApi;
                return int.TryParse(base.Something, out timerValueFromApi) ? (int?) timerValueFromApi : null; 

            }
            set
            {
                base.Something = value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : "0";
                NotifyPropertyChanged("TimerValueFromApi");
            }
        }
}

2 个答案:

答案 0 :(得分:2)

是的,它有效:

var xml = "<B><Something>5</Something></B>";
var b = (B) new XmlSerializer(typeof(B)).Deserialize(new StringReader(xml));
Console.WriteLine(b.TimerValueFromApi); // outputs "5"

答案 1 :(得分:1)

你可以像这样使用一些AfterDeserialization动作:

public interface IDeserializable
{
    void OnDeserialize();
}

public class A
{
    [XmlElement(ElementName = "Something", Form = XmlSchemaForm.Unqualified)]
    public string Something { get; set; }
}

public class B : A, IDeserializable
{
    [System.Xml.Serialization.XmlIgnore]
    public Int32 SomethingInt32
    {
        get;
        set;
    }

    public void OnDeserialize()
    {
        SomethingInt32 = Int32.Parse(Something);
    }
}

public class C
{
    public void Deserialize()
    {
        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(B));
        var b = ser.Deserialize(streamOrStringData) as B;
        b.OnDeserialize();
    }
}