我有一个问题,通过BitConverter.ToInt32将字节数组转换为int32.
mscorlib.dll中出现未处理的"System.ArgumentException"类型异常
附加信息:目标数组不够长,无法复制>集合中的所有项目.检查数组索引和长度
private void textBox2_TextChanged(object sender, EventArgs e)
{
byte[] StrToByte = new byte[9];
int IntHexValue;
StrToByte = Encoding.UTF8.GetBytes(textBox2.Text);
textBox4.Text = BitConverter.ToString(StrToByte);
IntHexValue = BitConverter.ToInt32(StrToByte, 0);
}
Run Code Online (Sandbox Code Playgroud)
据推测,文本的UTF-8表示textBox2
长度少于4个字节.BitConverter.ToInt32
需要4个字节的数据才能使用.
顺便说一句,目前还不清楚你想要实现的目标 - 但使用BitConverter.ToInt32
编码文本很少是有用的事情.
另外,在编码风格方面:
所以,即使你的代码是实际上是正确的,这将是更好的写法如下:
private void textBox2_TextChanged(object sender, EventArgs e)
{
byte[] encodedText = Encoding.UTF8.GetBytes(textBox2.Text);
textBox4.Text = BitConverter.ToString(encodedText);
int leadingInt32 = BitConverter.ToInt32(encodedText, 0);
// Presumably use the value here...
}
Run Code Online (Sandbox Code Playgroud)
(正如我所说,目前还不清楚你真正想要做什么,这就是为什么名称leadingInt32
不理想 - 如果我们知道你试图与价值联系的意义,我们可以在变量名中使用它. )