.net – 具有私有设置器的XmlSerializer和Collection属性

我有一个这样的简单的课
[Serializeable]
public class MyClass
{
    public MyClass()
    {
       this.MyCollection = new List<int>();
    }


    public List<int> MyCollection { get; private set;}
}

如果我尝试使用XmlSerializer反序列化,我得到一个错误,说MyCollection是只读的,不能被分配给.然而,我不想让setter公开,因为如果类的用户分配给它,这可能会导致各种问题. Fxcop正确地警告:Collection properties should be read only

不过在页面底部的社区添加内容是这样的:

XmlSerializer understands read-only
collections Collection
properties do not have to be
read-write for the XmlSerializer to
serialize and deserialize the contents
correctly. The XmlSerializer will look
for a method called Add on collection
properties that implement ICollection
or IEnumerable,and use that to
populate the collection when
deserializing an instance of the owner
type.

但是它似乎并不是这样(因为我得到了InvalidOperationException).我能做什么遵守保持属性设置者私有的最佳做法,同时仍然允许我使用XmlSerializer?

您的私人设置者正在引起问题. XmlSerializer类可以在下面给出的类中正常工作. XmlSerializer类是在引入私有设置器之前发明的,所以当它使用反射来扫描类类型时,可能不会正确地检查它.也许你应该把这个报告给微软作为一个bug.
public class MyClass
{
    private List<int> _myCollection;

    public MyClass()
    {
        _myCollection = new List<int>();
    }

    public List<int> MyCollection
    {
        get
        {
            return this._myCollection;
        }
    }
}

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念