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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


xml怎么加入图片路径
rss源错误怎么解决
文件后缀xml是什么意思
xml格式电子发票怎么获取
xml格式是什么意思
rss是什么意思啊
xml格式电子发票怎么打开
rss订阅源是什么意思
rss源是什么
xml注释怎么写
php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类