我有一个带有属性的类。我想知道我们是否可以设置属性,如 XmlAttributeAttribute.AttributeName。
这里ElementName属性是在编译时设置的,我想知道我们可以设置@运行时。
public class MyTestClass
{
[XmlElement(ElementName = "MyAttributeName")]
public int MyAttribute
{
get
{
return 23;
}
}
}
答案 0 :(得分:4)
您正在寻找XmlAttributeOverrides。
XmlAttributeOverrides attOv = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
attrs.XmlElements.Add(new XmlElementAttribute("MyAttributeName"));
attOv.Add(typeof(MyTestClass), "MyAttribute", attrs);
XmlSerializer serializer = new XmlSerializer(typeof(MyTestClass), attOv);
//...
答案 1 :(得分:0)
您需要实现ISerializable接口并覆盖以下函数,您可以在运行时设置属性(从列表或您可能想要的任何其他方式)
public Employee(SerializationInfo info, StreamingContext ctxt)
{
//Get the values from info and assign them to the appropriate properties
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}
//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}