如何序列化一个IList< T>? [英] How to serialize an IList<T>?

查看:186
本文介绍了如何序列化一个IList< T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个OR映射器(iBatis.Net),返回一个IList。

I've got an OR mapper (iBatis.Net) that returns an IList.

// IList<T> QueryForList<T>(string statementName, object parameterObject);
var data = mapper.QueryForList<Something>(statement, parameters);

我想在Web服务使用它的要返回数据1:1。当然,我不能返回的IList的一个WebMethod,因为它是一个接口,因此不序列化。

I'm trying to use it in an webservice an want to return the data 1:1. Of course I can't return IList in a WebMethod, because it is an interface and therefore not serializable.

我发现映射器是真的返回一个列表。但我害怕它转换为列表,当然,因为映射器内部工作可在未来的版本中改变(和它只是感觉脏)。

I found that the mapper is really returning an List. But I'm afraid to cast it to List because of course the mappers inner workings could change in future versions (and it just feels dirty).

这样,我......

So should I ...

a) return new List<Something>(data);

b) return (List<Something>)data;

c) // your solution here

非常感谢!

推荐答案

如果它真的是一个名单,其中,T&GT; ,但要防止改变,并仍工作,那么最高效的解决方案将试图将其转换为一个列表,如果失败,那么从其内容中创建一个新的列表,如:

If it really is a List<T> but you want to protect against change and have it still work, then the most performant solution will be to attempt to cast it to a list, and if that fails then create a new list from its content, e.g.

var data = mapper.QueryForList<T>(statement, parameters);
var list = data as List<T> ?? new List<T>(data);

不过,你提到你不能返回界面,因为它是一个Web服务。这可能是真实与ASMX和的XmlSerializer 类,但是如果你使用WCF构建Web服务,并使用的DataContractSerializer 然后会很乐意序列集合接口(同时作为输入和输出从服务)。这种类型的变化可能会更大一些比你正在寻找,但!

However, you mention that you can't return an interface because it's a web service. This may have been true with ASMX and the XmlSerializer class, but if you build the web service using WCF and use the DataContractSerializer then it will happily serialize collection interfaces (both as inputs to and outputs from the service). That type of change may be somewhat larger than you're looking for though!

这篇关于如何序列化一个IList&LT; T&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆