说我有一个这样的简单的课
[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.
原文链接:https://www.f2er.com/xml/292850.htmlpublic class MyClass { private List<int> _myCollection; public MyClass() { _myCollection = new List<int>(); } public List<int> MyCollection { get { return this._myCollection; } } }