如何将返回对象反序列化为正确的类类型?
这是定义了三个选项(SuccessType,WarningsType和ErrorsType)的XML标记:
<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;
答案 0 :(得分:0)
这是我当前的解决方案-创建一个返回所请求类型的通用方法。
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;
}
}
获取警告类型
var warningsType = readResponse.TopNode.GetItems<WarningsType>();
但是我必须先执行null测试
if (warningsType != null)
{
// code here
}