2010-03-10 66 views
0

我有一个有属性的类,我想知道是否可以设置属性,如 XmlAttributeAttribute.AttributeName。设置属性@运行时间

这里的ElementName属性是在编译时设置的,我想知道我们能不能设置@运行时间。

public class MyTestClass 
{ 
    [XmlElement(ElementName = "MyAttributeName")] 
    public int MyAttribute 
    { 
     get 
     { 
      return 23; 
     } 
    } 
} 
+0

你的问题有点不清楚,你可以尝试改述吗? – Kane 2010-03-10 08:34:54

+0

@Lasse V. Karlsen感谢格式化:) – Ravisha 2010-03-10 10:16:31

回答

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); 
    //... 
+0

这就是我正在寻找。谢谢哥们 – Ravisha 2010-03-10 10:08:57

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

看一看在CodeProject

+0

您可能是指IXmlSerializable - http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx – 2010-03-10 08:52:50

相关问题