Dilemma with XSD, Generics and C# Classes

喜欢而已 提交于 2020-02-04 06:35:46

问题


I have following simple XSD file:

  <xs:element name="Search" type="SearchObject"/>

  <xs:complexType name="SearchObject">
    <xs:choice>
      <xs:element name="Simple" type="SimpleSearch"/>
      <xs:element name="Extended" type="ExtendedSearch"/>
    </xs:choice>
  </xs:complexType>

  <xs:complexType name="SimpleSearch">
    <xs:sequence>
      <xs:element name="FirstName" type="xs:string"/>
      <xs:element name="LastName" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ExtendedSearch">
    <xs:sequence>
      <xs:element name="FirstName" type="xs:string"/>
      <xs:element name="LastName" type="xs:string"/>
      <xs:element name="Age" type="xs:int"/>
      <xs:element name="Address" type="xs:string"/>
    </xs:sequence>
  </xs:complexType>

I use Visual Studio Shell like this:

xsd XMLSchema.xsd /c

Basically /c stands for generating C# classes out of XMLSchema.xsd.

The classes then look something like this one:

[System.Xml.Serialization.XmlRootAttribute("Search", Namespace="http://tempuri.org/XMLSchema.xsd", IsNullable=false)]
public partial class SearchObject {

    private object itemField;

    [System.Xml.Serialization.XmlElementAttribute("Extended", typeof(ExtendedSearch))]
    [System.Xml.Serialization.XmlElementAttribute("Simple", typeof(SimpleSearch))]
    public object Item {
        get {
            return this.itemField;
        }
        set {
            this.itemField = value;
        }
    }
}

My first question is why is the property "Item" not called "Search" as I have set inside xsd file on that element?

My second question is why is property Item of type object? I have set a choice inside my xsd file and I would like the c# code to look more like this:

public partial class SearchObject<T> where T : SimpleSearch, where T : ExtendedSearch
{
    public T Search
    {
       get ...
       set ...
    }
}

I would like to have somehow an generic class that allows only the types which I have specified inside the choice block in xsd file which are in my case SimpleSearch and ExtendedSearch.

Is that even possible and if yes how do I get it right?


回答1:


Choice in xsd means you could have one of the different object types declared. And because of that, the xsd.exe generates an object(always named Item) instead of a strong type. See: http://msdn.microsoft.com/en-us/library/sa6z5baz(v=vs.85).aspx. You have to check during run time what the object type is:

ExtendedSearch extendedSearch = null;
SimpleSearch simpleSearch = null;
if(Item is ExtendedSearch)
 extendedSearch = (ExtendedSearch)Item;
else if(Item is SimpleSearch)
 simpleSearch = (SimpleSearch)Item;


来源:https://stackoverflow.com/questions/16574822/dilemma-with-xsd-generics-and-c-sharp-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!