如何将返回对象反序列化为正确的类类型?
这是XML标记,定义了三个选项(SuccessType,WarningsType和ErrorsType):
<xs:element name="TopNode">
<xs:complexType>
<xs:choice>
<xs:sequence>
<xs:element name="Success" type="SuccessType">
<xs:annotation>
<xs:documentation xml:lang="en">Success element.</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="Warnings" type="WarningsType" minOccurs="0">
<xs:annotation>
<xs:documentation xml:lang="en">Warning element.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
<xs:sequence>
<xs:element name="Errors" type="ErrorsType">
<xs:annotation>
<xs:documentation xml:lang="en">Error types element.</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:choice>
</xs:complexType>
这是c#中生成的类
public partial class TopNode
{
[System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType), Order=0)]
[System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType), Order=0)]
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType), Order=0)]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
this.RaisePropertyChanged("Items");
}
}
}
WarningsType的出现可以为零。以下是我如何投射并查找Web服务返回的结果中是否存在WarningsType。
var warningTypes = readResponse.TopNode.Items.FirstOrDefault(r => r.GetType() == typeof(NamespaceA.WarningsType)) as NamespaceA.WarningsType;
if (warningTypes != null) { // my code... }
如何删除搜索和转换为正确的类类型的需要,并使下面的可能?
var warningTypes = readResponse.TopNode.WarningsType;
这是我当前的解决方案 - 创建一个返回所请求类型的泛型方法。
public partial class TopNode
{
public T GetItem<T>()
{
var result = Items.FirstOrDefault(r => r.GetType() == typeof(T));
return (T)result;
}
public List<T> GetItems<T>()
{
var results = Items.Where(r => r.GetType() == typeof(T)).Select(r => (T)r).ToList();
return (List<T>)results;
}
}
获取WarningType
var warningsType = readResponse.TopNode.GetItems<WarningsType>();
但是在使用之前我必须执行null测试
if (warningsType != null)
{
// code here
}