解决WebService 中泛型接口不能序列化问题
本来要定义WebServices 方法返回一泛型接口集合IList,系统提示不能序列化泛型接口集合
1 [WebMethod]
2 public IList<Employee> GetEmployeeList()
3 {
4 IFormatter formatter = new SoapFormatter();
5 MemoryStream mStream = new MemoryStream();
6
7 Employee em1 = new Employee();
8 em1.EmployeeID = 1;
9 em1.FirstName = "jack";
10 em1.LastName = "josn";
11 IList<Employee> list = new List<Employee>();
12 list.Add(em1);
13 list.Add(em2);
14 return list;
15
参考了相关的资料,可以有两种解决办法,一:用List<>泛型集合替代IList<>泛型接口集合。
二.将List<>泛型集合序列化为二进制形式,进行传递。
1 /// <summary>
2 /// List泛型集合替代IList
3 /// </summary>
4 /// <returns></returns>
5 [WebMethod]
6 public List<Employee> GetEmployeeList()
7 {
8 IFormatter formatter = new SoapFormatter();
9 MemoryStream mStream = new MemoryStream();
10
11 Employee em1 = new Employee();
12 em1.EmployeeID = 1;
13 em1.FirstName = "jack";
14 em1.LastName = "josn";
15 List<Employee> list = new List<Employee>();
16 list.Add(em1);
17 return list;
18 }
19
20 /// <summary>
21 /// 以二进制形式进行传递,客户端需进行返序列化
22 /// </summary>
23 /// <returns></returns>
24 [WebMethod]
25 public byte[] GetEmployeeListByteArray()
26 {
27 Employee em1 = new Employee();
28 em1.EmployeeID = 1;
29 em1.FirstName = "jack";
30 em1.LastName = "josn";
31 IList<Employee> list = new List<Employee>();
32 list.Add(em1);
33 IFormatter formatter = new BinaryFormatter();
34 MemoryStream mStream = new MemoryStream();
35 byte[] bs;
36 if (list != null)
37 {
38 formatter.Serialize(mStream,list);
39 bs = mStream.ToArray();
40 }
41 else
42 {
43 bs = new byte[0];
44 }
45 return bs;
46
客户端反序列化代码
1 protected void CallService()
2 {
3 WebService ws = new WebService();
4 byte[] bs = ws.GetEmployeeListByteArray();
5 IList<Employee> list = null;
6 try
7 {
8 MemoryStream ms = new MemoryStream(bs); //创建Memory流对象
9 BinaryFormatter formatter = new BinaryFormatter();
10 list = (List<Employee>)formatter.Deserialize(ms); //反序列化
11 }
12 catch (Exception ex)
13 {
14 Response.Write("<script language='javaScript'>alert('"+ex.Message+"');</script>");
15 }
16
非泛型集合的IList接口进行传递时,只需在方法前标识[XmlInclude(typeof(类型)]即可。
1 [WebMethod]
2 [XmlInclude(typeof(Employee))]
3 public IList GetArticleList()
4 {
5 IList result = new ArrayList();
6 for (int i = 0; i < 20; i++)
7 {
8 DateTime time = DateTime.Now.AddDays(i);
9 Employee em = new Employee();
10 em.LastName = "jack";
11 em.EmployeeID = 11;
12 result.Add(em);
13 }
14 return result;
15 }
16