简体   繁体   English

数据合同的序列化异常

[英]serialization exception with datacontract

this is what it says: Type 'ItemType[]' with data contract name 'ArrayOfItemType:ItemType' is not expected. 这就是它的意思:不应使用数据协定名称为“ ArrayOfItemType:ItemType”的类型为“ ItemType []”。 Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer. 考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型的列表中-例如,通过使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型的列表中。

the code is pretty basic 代码很基本

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

the object im trying to serialize is 我试图序列化的对象是

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

derived from the class: 从类派生:

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

This happens because you serialize an array. 发生这种情况是因为您序列化了一个阵列。 But in the parameters passed to the constructor class instead of an array. 但是在传递给构造函数类的参数而不是数组中。

Replace 更换

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

on

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM