【问题标题】:serialization exception with datacontract数据合同的序列化异常
【发布时间】:2014-02-02 21:13:31
【问题描述】:

这就是它所说的: 不需要数据合同名称为“ArrayOfItemType:ItemType”的类型“ItemType[]”。考虑使用 DataContractResolver 或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。

代码很简单

DataContractSerializer ser = new DataContractSerializer(typeof(ItemType));
FileStream file = new FileStream("ItemType.xml", FileMode.Create); 
ser.WriteObject(file, itemTypes);

我试图序列化的对象是

protected static ItemType[] itemTypes = new ItemType[100];

从类派生:

[DataContract(Namespace = "ItemType")]

public class ItemType 
{    
    string name;       
    private int numberOfActions; 

    [DataMember()]
    public int[] codeOfAction = new int[10];
    [DataMember()]
    public int[] recipeType;
    [DataMember()]
    public int[] recipeNum;

    public ItemType()
    {
        this.name = " ";        
        this.recipeType = new int[10];
        this.recipeNum = new int[10];
        this.recipeType[0] = 0;
    }
    [DataMember]
    public string ItemName
    {
        get {return name;}
        set { name = value; }
    }
    [DataMember]
    public int NumberOfAction
    {
        get { return numberOfActions; }
        set { numberOfActions = value; }  
    }    
}

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    这是因为您序列化了一个数组。但是在参数中传递给构造函数类而不是数组。

    替换

    DataContractSerializer ser = new DataContractSerializer(typeof(ItemType));
    

    DataContractSerializer ser = new DataContractSerializer(typeof(ItemType[]));
    

    【讨论】:

      猜你喜欢
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2023-03-25
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多