如何在XSD数据合同中指定通用的Type参数?

时间:2012-03-12 11:28:00

标签: c# wcf xsd datacontracts wscf

我有一个Webservice方法调用的请求和响应数据协定对

  <xs:element name="GetUserOptionsRequest">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="OptionType" type="entities:UserOption" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="GetUserOptionsResponse">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="Options" type="entities:UserOption" minOccurs="0" maxOccurs="unbounded"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

问题是我想要的是一种说法(伪代码)

GetUserResponse response = GetuserOptions(new GetUserOptionsRequest(Type T))

根据我传递的类型,让响应包含IList。

使用我上面的数据契约XSD,当我只想指定一个Type定义时,它期望在请求对象中有一个类的实例。

真的,我想我想要的是什么

GetUserResponse<T> response = GetUserOptions(new GetUserOptionsRequest<T>());

但我不确定如何在XSD中指定泛型类/方法。任何人都可以指出我在一篇好文章或解释我如何在XSD中定义它吗?

我也在使用WSCF blue进行代码生成。

1 个答案:

答案 0 :(得分:1)

不幸的是,不可能在XSD中使用 open generics 定义类型。

实际上,XSD根本没有表示泛型类型参数的本地方式。但是,如果要从XSD架构中生成 .NET类型,则可以通过使用包含mimic closed generic arguments元素的<xsd:annotation>的类型进行装饰来<xsd:appinfo>

<xs:element name="Foo">
    <xs:complexType>
        <xs:sequence>
            ...
        </xs:sequence>
        <xs:annotation>
            <xs:appinfo>
                <GenericType Name="FooOf{0}{#}"
                             Namespace="...">
                    <GenericParameter Name="string"
                                      Namespace="http://www.w3.org/2001/XMLSchema" />
                </GenericType>
            </xs:appinfo>
        </xs:annotation>
    </xs:complexType> 
</xs:element>

此XSD架构将在.NET类型系统中表示为类型Foo<string>的类。请注意,在此示例中,泛型参数指定为string,但没有任何内容阻止您在具有不同泛型参数的多个合同中重用相同的XSD元素定义。

另请注意,GenericType元素是不是 XSD标准的一部分,只能由.NET代码生成工具解释。