反序列化将类似于:
var serializer = new XmlSerializer(typeof(T));
T obj = (T)serializer.Deserialize(new StringReader(value));
可以通过多种方式设置属性。首选是在类型之间有一些共性,也许是接口:
interface IFoo {
string property1 { get; }
}
和:
T DeSeriableXMLToObject<T>(string value) where T : IFoo {
var serializer = new XmlSerializer(typeof(T));
T obj = (T)serializer.Deserialize(new StringReader(value));
if(obj.property1 == "200") { ...}
return obj;
}
另一种选择是反射或dynamic
:
T DeSeriableXMLToObject<T>(string value) {
var serializer = new XmlSerializer(typeof(T));
dynamic obj = serializer.Deserialize(new StringReader(value));
if(obj.property1 == "200") { ...}
return obj;
}
顺便提一句; DeSeriableXMLToObject<T>
看起来......有点时髦的名字。我可以建议只是Deserialize<T>
或DeserializeXml<T>
吗?