[英]Set Attribute @ run time
I have a class with a property in it.I want to know if we can set the attribute such as XmlAttributeAttribute.AttributeName. 我有一个带有属性的类,我想知道是否可以设置XmlAttributeAttribute.AttributeName这样的属性。
Here the ElementName attribute is set at compile time,i want top know can we set @ run time. 这里的ElementName属性是在编译时设置的,我想首先知道我们可以设置@运行时。
public class MyTestClass
{
[XmlElement(ElementName = "MyAttributeName")]
public int MyAttribute
{
get
{
return 23;
}
}
}
You are looking for XmlAttributeOverrides . 您正在寻找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);
//...
You will need to implement ISerializable interface and override the following functions in which you can set attributes at run time(from a list or any other way you might want) 您将需要实现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);
}
Have a look at CodeProject 看看CodeProject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.