将数组列表对象转换为 byte[]

本文关键字:byte 转换 数组 列表 对象 | 更新日期: 2023-09-27 18:34:07

我有一个名为 list 的 araylist 对象,在这里我想将我的 arraylist 对象转换为 byte[],同时执行以下编码,它给出了一个错误:"源数组中至少有一个元素无法转换为目标数组类型"我的编码:

 byte[] obj= new byte[list.Count];
     list.CopyTo(obj); 

在这里,我的数组列表对象从 SSRS 报表返回报表数据。我想在这里做什么来解决这个问题。

将数组列表对象转换为 byte[]

看看这个(这将告诉你哪里可能有问题)

        List<object> list = new List<object>();
        list.Add((byte)1);
        list.Add((byte)0);
        list.Add("wtf");
        list.Add((byte)1);
        byte[] obj = list.OfType<byte>().ToArray();
        if(obj.Length!=list.Count)
        {
            //Exception, not all objects in list is 'byte'
        }

如果你的意思是 ArrayList 包含类型 byte 的项目,那么请使用这样的语法:

byte[] obj = (byte[])list.ToArray(typeof(byte));

否则你想要什么不清楚,因为对象不能像那样转换为字节,所以请更好地解释。