XmlSerializer +多态性
给定一个(设计的)基类和一个子类,我们希望使用 XmlSerializer 通过 WCF 进行序列化。我们按照以下文章装饰一个集合(请参阅响应类):
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.aspx(请参阅备注部分)。
问题是,虽然似乎生成了正确的 WSDL,但 SVCUtil 生成了一个类文件,其中 GetUserResponse 类包含名为 Items 的属性。这与将 [XmlElement] 应用于数组有关吗?尽管 XmlArray 元素没有 Type 属性。
提前致谢。
[Serializable]
[XmlType]
public class UserBase
{
public int Id {get;set;}
}
[Serializable]
[XmlType]
public class BasicUser : UserBase
{
public string UserName {get;set;}
}
[Serializable]
[XmlType]
public class SuperUser : UserBase
{
public string UserName {get;set;}
public bool SpecialLevel {get;set;}
}
[Serializable]
[XmlType]
public class GetUserResponse
{
[XmlElement("Users", typeof(User)), XmlElement("SuperUsers", typeof(SuperUser))]
public List<UserBase> Users {get;set;}
}
Given a (contrived) base class, and a sub class we want to serialize via WCF using the XmlSerializer. We decorate a collection (see the response class) as per the article:
http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlelementattribute.aspx (see remarks section).
Issue is that although the correct WSDL seems to be generated, SVCUtil generates a class file where the GetUserResponse class contains a property named Items. Is this to do with applying [XmlElement] to an array? Although the XmlArray element doesn't have a Type property.
Thanks in advance.
[Serializable]
[XmlType]
public class UserBase
{
public int Id {get;set;}
}
[Serializable]
[XmlType]
public class BasicUser : UserBase
{
public string UserName {get;set;}
}
[Serializable]
[XmlType]
public class SuperUser : UserBase
{
public string UserName {get;set;}
public bool SpecialLevel {get;set;}
}
[Serializable]
[XmlType]
public class GetUserResponse
{
[XmlElement("Users", typeof(User)), XmlElement("SuperUsers", typeof(SuperUser))]
public List<UserBase> Users {get;set;}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您在集合属性上使用
[XmlElement]
,所以相应的 xml 将类似于:实际上没有任何地方可以为集合提供更好的名称 属性,
Items
除外。我想知道使用:为了构建: 是否会更好:
那么你将拥有一个
Users
属性。Because you are using
[XmlElement]
on the collection property, the corresponding xml is going to be something like:there isn't really anywhere it can get a better name for a collection property, other than
Items
. I wonder if it might be better to use:in order to build:
then you would have a
Users
property.