XmlSerializer + Polymorphism

前端 未结 1 368
北荒
北荒 2020-12-19 22:16

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:

相关标签:
1条回答
  • 2020-12-19 22:39

    Because you are using [XmlElement] on the collection property, the corresponding xml is going to be something like:

    <GetUserResponse>
        <Users>{this is a user}</Users>
        <Users>{this is a user}</Users>
        <SuperUsers>{this is a super user}</SuperUsers>
        <Users>{this is a user}</Users>
        <SuperUsers>{this is a super user}</SuperUsers>
    </GetUserResponse>
    

    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:

    [XmlArray("Users")]
    [XmlArrayItem("User", typeof(User))]
    [XmlArrayItem("SuperUser", typeof(SuperUser))]
    

    in order to build:

    <GetUserResponse>
        <Users>
            <User>{this is a user}</User>
            <User>{this is a user}</User>
            <SuperUser>{this is a super user}</SuperUser>
            <User>{this is a user}</User>
            <SuperUser>{this is a super user}</SuperUser>
        </Users>
    </GetUserResponse>
    

    then you would have a Users property.

    0 讨论(0)
提交回复
热议问题