Deserialize XML data into object
由于工作的需要,自己写了一个exmaple on 反序列 xml data 成 自定义的一个object:
主体: using System;
辅助: using System;
在这里我遇到几个问题: 1. 反序列时候XmlArray("emailcollection") 对应的变量不能被定义为 List, 只能定义为 array。 其实是错的。 可以被定义为 list。 [System.Xml.Serialization.XmlArray("emailcollection")]
2. 自定义的collection 要能使用foreach statoment,必须实现Getenumerator() 方法
微软解释
Type:
System.Collections.IEnumerator
An IEnumeratorobject that can be used to iterate through the collection. Theforeachstatement of the C# language (For Eachin Visual Basic) hides the complexity of the enumerators. Therefore,usingforeachis recommended,instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection,but they cannot be used to modify the underlying collection. Initially,the enumerator is positioned before the first element in the collection. TheResetmethod also brings the enumerator back to this position. At this position,theCurrentproperty is undefined. Therefore,you must call theMoveNextmethod to advance the enumerator to the first element of the collection before reading the value ofCurrent. Currentreturns the same object until eitherMoveNextorResetis called.MoveNextsetsCurrentto the next element. IfMoveNextpasses the end of the collection,the enumerator is positioned after the last element in the collection andMoveNextreturnsfalse. When the enumerator is at this position,subsequent calls toMoveNextalso returnfalse. If the last call toMoveNextreturnsfalse,Currentis undefined. To setCurrentto the first element of the collection again,you can callResetfollowed byMoveNext. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection,such as adding,modifying,or deleting elements,the enumerator is irrecoverably invalidated and its behavior is undefined. The enumerator does not have exclusive access to the collection; therefore,enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration,you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing,you must implement your own synchronization.
3. 反序列后,object 需要被添加。 添加时需要判定当前collection的状态,然后实习add,否则会进入deadlock然后得到stackoverexception public void Add(object o) _emails.Add(o as email); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |