为什么字典没有返回正确的键值?

时间:2019-04-29 23:39:41

标签: c# dictionary

我将键和值存储在字典中,但是问题是字典为特定键检索了错误的值。它检索array []变量中最后存储的值 我需要解决此问题的帮助

  public String Encrypt(String PlainText, String Key)
        {
            Dictionary<int, byte[]> PlainToCipherDic = new Dictionary<int, byte[]>();
            String EncryptedText = "";           

            for (int i = 0; i < PlainBytes.Length; i++)
            {
                    int XoredInt = Convert.ToInt32(PlainBytes[i]);
                    if (!PlainToCipherDic.ContainsKey(XoredInt))
                  {                   
                    int PlainInteger = XoredInt;               

                    EncryptedBytes[i * 2] = PlainBytes[i];                   
                    EncryptedBytes[i * 2 + 1] = Mapping[i];                   
                   array[0] = EncryptedBytes[i * 2];
                   array[1] = EncryptedBytes[i * 2+1];
                   PlainToCipherDic.Add(XoredInt, array);

                }
                else
                {
                   byte[] value;
                  PlainToCipherDic.TryGetValue(XoredInt, out value);
                  EncryptedBytes[i * 2] = value[0];
                 EncryptedBytes[i * 2+1] = value[1];

                }

            }
               EncryptedText = Encoding.ASCII.GetString(EncryptedBytes);

                //Console.WriteLine("PlainToCipherDic : " + PlainToCipherDic.TryGetValue(XoredBytes, out EncryptedBytes));
            return EncryptedText;
            }

1 个答案:

答案 0 :(得分:3)

无论如何,您都继续循环。找到后,您需要退出循环。