基于XmlChoiceIdentifier创建对象

本文关键字:创建对象 XmlChoiceIdentifier 基于 | 更新日期: 2023-09-27 18:15:30

我正在使用Activator(c#)动态创建对象,其中一个类看起来像:

class Driver
{
   Driver() { }
   [XmlChoiceIdentifier("ItemElementName")]
   [XmlElement("Bit16", typeof(DriverModule))]
   [XmlElement("Bit32", typeof(DriverModule))]
   [XmlElement("Bit64", typeof(DriverModule))]
   [XmlElement("Unified", typeof(DriverUnified))]
   public object Item { get; set; }
   [XmlIgnore]
   public ItemChoiceType ItemElementName { get; set; }
   // ... other serialization methods
}

当我使用Activator创建Driver类的实例时,我得到以下对象:

obj.Item = null;
obj.ItemElementName = "Bit16"

ItemElementName是默认设置的,因为它是enum,但是如果它基于这个enum,如何设置Item ?再一次,我用Activator动态地创建了许多对象,所以我不能硬编码它-有可能在类中获得此信息并正确创建Item属性?

非常感谢!

基于XmlChoiceIdentifier创建对象

ItemElementName设置为ItemChoiceType.Bit16,因为这是枚举中的第一项。因此它的值是0,但你可以看到它是Bit16。通过Activator,您创建了一个新实例。如果你没有设置参数来设置你的属性,那么它们的值将是默认值。

我看到你有那里的XmlChoiceIdentifier和其他XmlSerializer的东西。这个属性的目的是:

  1. 不序列化ItemElementName属性
  2. 根据Item的序列化值反序列化后恢复ItemElementName

根据给定的信息,这就是我能告诉你的…

下面是使用XmlSerializer和XmlChoiceIdentifier的示例:

public class Choices
{
    [XmlChoiceIdentifier("ItemType")]
    [XmlElement("Text", Type = typeof(string))]
    [XmlElement("Integer", Type = typeof(int))]
    [XmlElement("LongText", Type = typeof(string))]
    public object Choice { get; set; }
    [XmlIgnore]
    public ItemChoiceType ItemType;
}
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
    Text,
    Integer,
    LongText
}
class Program
{
    static void Main(string[] args)
    {
        Choices c1 = new Choices();
        c1.Choice = "very long text"; // You can put here a value of String or Int32.
        c1.ItemType = ItemChoiceType.LongText; // Set the value so that its type match the Choice type (Text or LongText due to type of value is string).
        var serializer = new XmlSerializer(typeof(Choices));
        using (var stream = new FileStream("Choices.xml", FileMode.Create))
            serializer.Serialize(stream, c1);
        // Produced xml file.
        // Notice:
        // 1. LongText as element name
        // 2. Choice value inside the element
        // 3. ItemType value is not stored
        /*
        <?xml version="1.0"?>
        <Choices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <LongText>very long text</LongText>
        </Choices>
        */
        Choices c2;
        using (var stream = new FileStream("Choices.xml", FileMode.Open))
            c2 = (Choices)serializer.Deserialize(stream);
        // c2.ItemType is restored
    }
}