Web Service接口返回泛型的问题(System.InvalidCastException: 无法将类型为“System.Collections.Generic.List`1[System.String]”的对象强制转换为类型“System.String[]”)

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

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

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

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

        [WebMethod]
        public List<string> HelloWorld()
        {
            List<string> strList = new List<string>();
            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<string>泛型就没有问题了。 本人觉得这个问题很奇怪,可能是VS2008的bug。写出来只是希望大家在使用时能够注意这个情况。

解释如下:

这是不是BUG,因为你是用了泛型,所以在序列化的时候要指定它的类型,加上:
[XmlInclude(typeof(类型))] 就OK了。

感觉不是List不能序列化的问题,而是List在序列化以后,他的本质还是array,因此,如果在一个Webservice里存在两种序列化方式的的方法,就会存在问题。

Web Service在传输对象的时候,是把对象先序列化成为xml或者数据流,string对象是可以序列化,而List不是可序列化对象,所以在System.Xml.Serialization.XmlSerializer.Serialize 序列化的时候出错了

原文地址:https://www.cnblogs.com/ileaves/p/3405739.html