A strange problem occurred when using C # To write a web service. The type of the returned value is generic (I used a list-like <string> interface). During the test, I found that there was always an error that could not be converted to an object. I was puzzled.
Later, with the help of my colleagues, I found the rule. Before an interface whose return value is a generic type, an error will occur if the return value is an interface of a string array, if you put the returned generic interface behind the interface of the returned string array, no problem will occur.
The Code is as follows:
[Webmethod] <br/> Public String [] helloworld1 () <br/>{< br/> string [] STR = new string [2]; <br/> STR [0] = "hello"; <br/> STR [1] = "world! "; <Br/> return STR; <br/>}</P> <p> [webmethod] <br/> public list <string> helloworld () <br/>{< br/> List <string> strlist = new list <string> (); <br/> strlist. add ("hello"); <br/> strlist. add ("world! "); <Br/> return strlist; <br/>}< br/>
At this time, an error occurs when you call helloworld. The error is as follows:
System. invalidoperationexception: An error occurred while generating the XML document. ---> System. invalidcastexception: the object of the type "system. Collections. Generic. List '1 [system. String]" cannot be forcibly converted to the type "system. String []". <Br/> in Microsoft. XML. serialization. generatedassembly. xmlserializationwriter1.write2 _ arrayofstring (Object O) <br/> in Microsoft. XML. serialization. generatedassembly. arrayofstringserializer1.serialize (Object objecttoserialize, xmlserializationwriter writer) <br/> in system. XML. serialization. xmlserializer. serialize (xmlwriter, object o, xmlserializernamespaces namespaces, string encodingstyle, string ID) <br/> --- end of internal exception stack trace --- <br/> in system. XML. serialization. xmlserializer. serialize (xmlwriter, object o, xmlserializernamespaces namespaces, string encodingstyle, string ID) <br/> in system. XML. serialization. xmlserializer. serialize (textwriter, object O) <br/> in system. web. services. protocols. xmlreturnwriter. write (httpresponse response, stream outputstream, object returnvalue) <br/> in system. web. services. protocols. httpserverprotocol. writereturns (object [] returnvalues, stream outputstream) <br/> in system. web. services. protocols. webservicehandler. writereturns (object [] returnvalues) <br/> in system. web. services. protocols. webservicehandler. invoke () <br/>
Change helloworld and helloworld1 to a string array or a list <string> generic type. I think this problem is very strange. It may be a bug in vs2008. I just hope you can pay attention to this situation when using it.
I hope you can find out the problem. I am very grateful.