在C#中使用XmlChoiceIdentifier进行序列化

时间:2018-11-08 11:33:10

标签: c#

我尝试使用XmlChoiceIdentifier在C#中序列化简单对象:

public class ChargesConditions
{
    public string supplierBillID;
    public ChargesConditions() { }
}

public class PayersConditions
{
    public string payerIdentifier;
    public PayersConditions() { }
}

[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
    Payers,
    Charges
}

public class Choices
{
    [XmlChoiceIdentifier("ItemType")]
    [XmlElement("PayersConditions", Type = typeof(PayersConditions))]
    [XmlElement("ChargesConditions", Type = typeof(ChargesConditions))]
    public object Choice;

    [XmlIgnore]
    public ItemChoiceType ItemType;
}

class Program
{
    static void Main(string[] args)
    {
        ChargesConditions charge = new ChargesConditions();
        charge.supplierBillID = "123";
        Choices c1 = new Choices();
        c1.ItemType = ItemChoiceType.Charges;
        c1.Choice = charge;

        var serializer = new XmlSerializer(typeof(Choices));
        using (var stream = new FileStream("Choices.xml", FileMode.Create))
            serializer.Serialize(stream, c1);
    }
}

程序在行上生成InvalidOperationException异常

var serializer = new XmlSerializer(typeof(Choices));

我的程序出了什么问题? XmlSerializer是否只能使用简单类型(如int,string)?

0 个答案:

没有答案