[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?
public class MyClass { private List<int> _myCollection; public MyClass() { _myCollection = new List<int>(); } public List<int> MyCollection { get { return this._myCollection; } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。