2010-07-26 116 views
1

我使用此代码收到异常;
InnerException: System.InvalidOperationException
Message=The specified type was not recognized: name='Person',
namespace='', at "<"Contact xmlns=''>.
以下是我认为的相关代码。
Person类是没有任何注解的裸类,并且不从任何接口继承。
如何使反序列化识别我的类? 在此先感谢。使用XmlSerializer进行反序列化时出错

public class Contacts : List<Contact.Contact> 
{ 
    private void PopulateTypeList() 
    { 
     types.Add(typeof(Contact.Contact)); 
     types.Add(typeof(Contact.Company)); 
     types.Add(typeof(Contact.Person)); 
     types.Add(typeof(ContactData.Direction)); 
     types.Add(typeof(ContactData.email)); 
     types.Add(typeof(ContactData.Phone)); 
    } 

    public void Load() 
    { 
     try 
     { 
      using (System.Xml.XmlReader stream = System.Xml.XmlReader.Create(fileName)) 
      { 
       XmlSerializer xs = new XmlSerializer(typeof(List<Contact.Contact>)); 
       // this roundabout way is for making it possible for this class to 
       // inherit from List<Contact.Contact> and still use a method that 
       // gives the stored data as an value in the object 
here is error List<Contact.Contact> data = 
        (List<Contact.Contact>)xs.Deserialize(stream); 
       this.Clear(); 
       this.AddRange(data); 
      } 
     } 
     catch (System.IO.FileNotFoundException) 
     { 
      // do nothing; no file, new database 
     } 
    } 

    public void Save() 
    { 
     using (System.Xml.XmlWriter stream = System.Xml.XmlWriter.Create(fileName)) 
     { 
      XmlSerializer xs = 
       new XmlSerializer(typeof(List<Contact.Contact>), types.ToArray()); 
      List<Contact.Contact> data = this.ToList(); 
      xs.Serialize(stream, data); 
     } 
    } 
+0

幽默我:尝试反序列化到一个数组。 – 2010-07-26 07:37:18

+0

@史蒂文:我很抱歉,我不明白,你能解释一下吗? – Gorgen 2010-07-26 07:43:32

+1

@Steven:我想你的意思是我应该搜索“反序列化到数组”。谢谢你提出一个好的搜索。 – Gorgen 2010-07-26 07:52:31

回答

0

尝试通过类型列表中给您deserialisation创建串行器:

XmlSerializer xs = new XmlSerialiser(typeof(List<Contact.Contact>), types.ToArray()); 
+0

好吧,这工作得很好,谢谢你发现错误。之前应该看到这个... – Gorgen 2010-07-26 07:51:37

相关问题