相同字节显示不同的结果

时间:2013-12-03 14:07:18

标签: c# .net byte

在不更改byte [] numArray的情况下,即使字节保持完全相同,两个消息框也会显示不同的输出。我糊涂了。

第一个MessageBox的结果:  stream:stream to =“”version =“1.0”xmlns:stream =“http://etherx.jabber.org/streams”>

第二个MessageBox的结果: ˚F^ V

第三个MessageBox:“匹配”

MessageBox.Show(System.Text.Encoding.UTF8.GetString(numArray));
byte[] num1 = numArray;
byte[] encrypted =  getEncryptedInit(numArray);
MessageBox.Show(System.Text.Encoding.UTF8.GetString(numArray));
byte[] num2 = numArray;
if (num1.SequenceEqual<byte>(num2) == true)
{
    MessageBox.Show("Match");
}

1 个答案:

答案 0 :(得分:6)

getEncryptedInit必须修改numArray

的内容

由于num1num2都指向numArray,因此它们当然是等效的。

请记住,数组是引用类型,因此当您说num1 = numArray时,您只需将num1变量指向numArray指向的内存中的相同位置。如果你真的想捕捉numArray在特定时间点的样子,你必须复制它,而不是仅仅做一个简单的任务。

考虑以下示例:

void DoStuff(byte[] bytes) {
  for (int i = 0; i < bytes.Length; i++) {
    bytes[i] = 42;
  }
}

bool Main() {
  // This allocates some space in memory, and stores 1,2,3,4 there.
  byte[] numArray = new byte[] { 1, 2, 3, 4 };

  // This points to the same space in memory allocated above.
  byte[] num1 = numArray;

  // This modifies what is stored in the memory allocated above.
  DoStuff(numArray);

  // This points to the same space in memory allocated above.
  byte[] num2 = numArray;

  return (num1 == num2 == numArray); // always true
}
相关问题