如何将ArrayList中的第一项复制/转换为C#中的字符串

本文关键字:复制 一项 转换 字符串 ArrayList | 更新日期: 2023-09-27 18:20:38

我正试图将数组列表的第一项复制到字符串变量中。我做了以下操作,但它返回System.Byte[]。请帮助

    for(i=0; i<= ArrayList.Count;i++)
    {
    String TEST = ArrayList[i].ToString();
    }

如何将ArrayList中的第一项复制/转换为C#中的字符串

它返回System.Byte[]

.ToString()的默认行为只是输出对象类型的名称。它在某些类型(如值类型)中被重写,以显示对象值的某些表示形式。由于ToString没有被数组重写,所以您只看到类型名称。

有多种方法(ASCII、UTF8、Unicode)可以将Byte[]转换为字符串,因此需要指定使用哪种方法。如果您想使用系统的默认编码,请使用

System.Text.Encoding.Default.GetString(ArrayList[i]);

这意味着,代码返回一个对象,即System.Byte[]数组。

ArrayList[i].ToString(); // System.Byte[]

无论你做了多少次,它都会恢复原状。

使用此替代

using System.Text; // <-- add this
// inside the code
for(i = 0 ; i <= ArrayList.Count ; i++ )
{
   string TEST = Encoding.UTF8.GetString(ArrayList[i]);
}

这将把字节编码为数据的字符串表示。