XmlElement 继承
XmlElement Inheritance
我想知道是否可以继承 XmlElement 字段,例如
public class A{
[XmlElement(ElementName = "Something", Form = XmlSchemaForm.Unqualified)]
public string Something{ get; set; }
}
public class B: A
{
}
并且在使用 class B 对象时,我可以拥有可以通过尝试解析以生成 Int32 等操作来操纵的 Something XmlElement 字段吗?
谢谢
//编辑
这是我要在另一个 class.
中用这个 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");
}
}
}
是的,有效:
var xml = "<B><Something>5</Something></B>";
var b = (B) new XmlSerializer(typeof(B)).Deserialize(new StringReader(xml));
Console.WriteLine(b.TimerValueFromApi); // outputs "5"
您可以像这样使用一些 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();
}
}
我想知道是否可以继承 XmlElement 字段,例如
public class A{
[XmlElement(ElementName = "Something", Form = XmlSchemaForm.Unqualified)]
public string Something{ get; set; }
}
public class B: A
{
}
并且在使用 class B 对象时,我可以拥有可以通过尝试解析以生成 Int32 等操作来操纵的 Something XmlElement 字段吗?
谢谢
//编辑
这是我要在另一个 class.
中用这个 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");
}
}
}
是的,有效:
var xml = "<B><Something>5</Something></B>";
var b = (B) new XmlSerializer(typeof(B)).Deserialize(new StringReader(xml));
Console.WriteLine(b.TimerValueFromApi); // outputs "5"
您可以像这样使用一些 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();
}
}