C#接收WCF返回接口类型的数组数据并转换为具体类型数组

作者:陆金龙    发表时间:2015-07-23 23:48   


object类型的数组在转换为基元类型数组或用户自定义类型数组时,不能像单个对象的转换一样使用as语法或者强制转换。除了通过for循环遍历处理,还有一种比较简洁的处理方法,即使用linq语法的Select方法并在lambda表达式中完成转换,然后使用ToArray()得到数组。以下是一个调用WCF应用场景的实例:
 
假设AComputer是实现了接口IComputer的类, IHardWareService是提供硬件设备信息的服务接口,其中的GetComputerList操作返回接口类型的集合数据。在AHardWareService服务中实现了 IHardWareService中的GetComputerList(),但是注意数组中每一项是将AComputer类型的实例赋值给了IComputer类型的变量。
 
[ServiceContract]
public interface IHardWareService
{
    [OperationContract]
    [ServiceKnownType(typeof(AComputer))]
    List<IComputer> GetComputerList();
}
public class AHardWareService :  IHardWareService
{
      public List<IComputer> GetComputerList()
     {
          List<IComputer> list =new List<IComputer>();
          IComputer cpt1 = new AComputer("computer1");
          IComputer cpt2 = new AComputer("computer1");
          IComputer cpt3 = new AComputer("computer1");
          list.Add(cpt1);
          list.Add(cpt2);
          list.Add(cpt3);
          return  list;
     }
}
 
在客户端通过服务代理对象访问AHardWareService服务,实际返回类型为object[],数组中每一项的数据实际类型则为AComputer。
private AHardWareServiceClient serviceClient=new AHardWareServiceClient();
object[] objs =serviceClient.GetComputerList();
//AComputer[] computers =(AComputer[] )objs;//这样调用会报错,提示无法将object[]类型强制转换为AComputer[] 
//AComputer[] computers =objs as AComputer[] ;//这样调用也不会成功,同样报错。
AComputer[] computers = objs.Select(o=>o as AComputer).ToArray();//成功转换的方法
 
当然如果要转换为基元类型的数组,稍作修改即可以实现,如
string[] computerNames =objs.Select(o=>o.ToString()).ToArray();         //转换为字符串数组
int[] numbers =Numberobjs.Select(n=>Convert.ToInt32(n)).ToArray(); //转换为int数组