简体   繁体   English

周转基金。 服务通用方法

[英]WCF. Service generic methods

How can I use generic methods in wcf service?如何在 wcf 服务中使用泛型方法?

I wrote this code:我写了这段代码:

[OperationContract]
void AddItem<T>(T item);

But I receive the following Error:但我收到以下错误:

Type 'T' cannot be exported as a schema type because it is an open generic type.类型“T”不能作为架构类型导出,因为它是一个开放的泛型类型。 You can only export a generic type if all its generic parameter types are actual types.如果所有泛型参数类型都是实际类型,则只能导出泛型类型。

You simply can't.你根本做不到。 It's not possible to do that, as soap does not support this.这是不可能的,因为肥皂不支持这一点。 See this article , which mentions how to get around generics, by creating an intermediate local object that is called and casts the object before calling the WCF operation.请参阅这篇文章,其中提到了如何绕过泛型,方法是创建一个中间本地对象,该对象在调用 WCF 操作之前被调用并转换该对象。

You shouldn't be trying to do this.你不应该试图这样做。 In a SOAP enabled web service all types need to be known when the WSDL is published so that clients would be capable of generating a proxy.在支持 SOAP 的 Web 服务中,在发布 WSDL 时需要知道所有类型,以便客户端能够生成代理。 Generics simply don't exist in the SOAP specification. SOAP 规范中根本不存在泛型。 SOAP is intended to be interoperable and generics don't exist in all languages. SOAP 旨在实现互操作,并且并非所有语言都存在泛型。

可以使用数据契约中的有界泛型类型,但必须是服务契约中指定的类型参数,并作为具有有效数据契约的指定类型参数

As all the others have already mentioned, WCF and SOAP do not support this.正如所有其他人已经提到的,WCF 和 SOAP 不支持这一点。 The issue is: anything you pass back and forth between client and server must be expressible in a XML schema document.问题是:您在客户端和服务器之间来回传递的任何内容都必须可以在 XML 模式文档中表达。

XML schema supports all the usual atomic types, like string, int, datetime - and it supports complex types made up of those atomic types, and it supports inheritance. XML 模式支持所有常见的原子类型,如字符串、整数、日期时间——并且支持由这些原子类型组成的复杂类型,并且支持继承。

But XML schema has no support for generics - and thus, anything you exchange via WCF and SOAP cannot be generic - you need to use concrete, non-generic types only.但是 XML 模式不支持泛型——因此,您通过 WCF 和 SOAP 交换的任何东西都不能是泛型的——您只需要使用具体的非泛型类型。

I don't know of any way around this, either.我也不知道有什么办法可以解决这个问题。 It's a limitation and you have to live with it for now.这是一个限制,你现在必须忍受它。

The error says that open types are not allowed.该错误表示不允许打开类型。 What probably is allowed is something like:可能允许的是:

[OperationContract]
void AddItem<T>(T item) where T : MyBaseType;

Ofcourse, all inherited types should be added with the KnownType attribute.当然,所有继承的类型都应该加上KnownType属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM