代码改变世界

2008-4-2 .Net CF2.0中序列化的一些疑难杂症

2008-04-02 17:08  老羽  阅读(480)  评论(2编辑  收藏  举报
 

今天碰到一问题,原本一直运行没问题的代码,突然出错了。序列化某个对象时总是失败,错误信息:

at System.Xml.Serialization.TypeContainer.AddType()
at System.Xml.Serialization.TypeContainer.AddType()
at System.Xml.Serialization.XmlSerializationReflector.AddIXmlSerializableType()
at System.Xml.Serialization.XmlSerializationReflector.AddType()
at System.Xml.Serialization.XmlSerializationReflector.FindType()
at System.Xml.Serialization.XmlSerializationReflector.FindType()
.....
 
对象也不复杂:大致如下:

public class UpLoaderEntity

{

        [XmlArray("FailedFiles", Namespace = "")]

        [XmlArrayItem("UploadFailedFile", Namespace = "", Type = typeof(UploadFile))] 

public List<UplodaFile> FailedFiles

        {

            get

            {

                if (this._FailedFiles == null)

                {

                    this._FailedFiles = new List<UplodaFile> ( );

                }

                return this._FailedFiles;

            }

        }

[XmlArray("FinishFiles", Namespace = "")]

    [XmlArrayItem("UploadFinishFile", Namespace = "", Type = typeof(string))]    
    public List<string> FinishFiles

    {

            get

            {

                if (this._FinishFiles == null)

                {

                    this._FinishFiles = new List<string> ( );

                }

                return this._FinishFiles;

            }

        }        
       //出问题的就是这2个属性,其余属性略
}

       google搜索了一下System.Xml.Serialization.TypeContainer.AddType()果然发现了同样命苦的人。地址如下:http://www.zorched.net/2007/02/04/more-net-compact-framework-woes/ 

当你用到集合时,特别是泛型时,又用到重命名元素,或限制某个元素时(XmlElement,XmlArray,XmlArrayItem等等),会碰到这个问题。而且上面的代码在Full Framework中是没有任何问题的。

解决方法,利用强类型。将List<UploadFile>改为UploadFileCollectoin;List<string> 改为 StringCollection;

[Serializable]

    public class UploadFileCollectoin : List<UploadFile>

    {   

}[Serializable]

public class StringCollection : System.Collections.ArrayList//List<string>    {}

奇怪的是,这里当StringCollection 继承List<string>时竟然也不行,我改为ArrayList才解决了这个问题,当然,直接改为数组是最简单的,不过数组在使用时不太方便。

(环境:.net cf2.0,coolpad8260机器,wince5.0系统)