How can I use generic methods in wcf service?
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. 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.
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. Generics simply don't exist in the SOAP specification. SOAP is intended to be interoperable and generics don't exist in all languages.
As all the others have already mentioned, WCF and SOAP do not support this. The issue is: anything you pass back and forth between client and server must be expressible in a XML schema document.
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.
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.
I don't know of any way around this, either. It's a limitation and you have to live with it for now.
Bounded generic types in data contracts can be used but must be specfied types parameters in the service contract and as the specified type parameters with valid data contracts
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.
精彩评论