Web Service接口返回泛型的怪异问题

      在使用C#写Web Service时遇到了个很奇怪的问题。返回值的类型是泛型(我用的是类似List)的接口,测试时发现总是报什么无法转换为对象的错误,百思不得其解。

      后来在同事的帮助下,发现了规律,在返回值是泛型的接口前面,只要有返回值是字符串数组的接口,就会发生错误,如果把返回泛型的接口放到返回字符串数组的接口后面,就没问题了。

      结合代码说明一下,代码如下:

[WebMethod] public string[] HelloWorld1() { string[] str = new string[2]; str[0] = "Hello "; str[1] = "World!"; return str; } [WebMethod] public List HelloWorld() { List strList = new List(); strList.Add("Hello "); strList.Add("World!"); return strList; }

     此时调用HelloWorld就会出现错误,错误如下:

System.InvalidOperationException: 生成 XML 文档时出错。 ---> System.InvalidCastException: 无法将类型为“System.Collections.Generic.List`1[System.String]”的对象强制转换为类型“System.String[]”。 在 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_ArrayOfString(Object o) 在 Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfStringSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer) 在 System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) --- 内部异常堆栈跟踪的结尾 --- 在 System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) 在 System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o) 在 System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue) 在 System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream) 在 System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues) 在 System.Web.Services.Protocols.WebServiceHandler.Invoke()

   将HelloWorld和HelloWorld1都改为string数组或List泛型就没有问题了。 本人觉得这个问题很奇怪,可能是VS2008的bug。写出来只是希望大家在使用时能够注意这个情况。

   希望能有高手指出问题所在,不胜感激。

你可能感兴趣的:(Web Service接口返回泛型的怪异问题)