C#字节具有相同内容的列表(或字典)数组不相等

时间:2014-03-24 15:15:03

标签: list dictionary byte bytearray equality

我有两个内容相同的列表。第一个添加了三个项目并再次删除了一个。第二个只添加了剩余的两个项目。然后我将两者都转换为字节数组,但字节数组不相等。它们在一个字节上不同。 有没有办法让两个“相等”列表具有与执行操作无关的相等字节数组?

我需要这个来将列表保存到包含RSA签名的文本文件中。但是,如果内存中的列表(过去对其执行的操作)不等于文本文件内容中新生成的列表,则我无法使用valide签名。

在我的应用程序中,我使用字典而不是列表,但这是相同的行为。

这是我的测试代码:

    static void Main(string[] args)
    {
        List<string> one = new List<string>();

        one.Add("hallo");
        one.Add("hallo1");
        one.Remove("hallo1");
        one.Add("hallo1");

        byte[] test = Program.ObjectToByteArray(one);
        Console.WriteLine(test.Length);



        List<string> two = new List<string>();

        two.Add("hallo");
        two.Add("hallo1");

        byte[] test1 = Program.ObjectToByteArray(two);
        Console.WriteLine(test1.Length);

        bool areEqual = false;
        int count = 0;
        if (test.Length == test1.Length)
        {
            areEqual = true;

            for (int i = 0; i < test.Length; i++)
            {
                if (test[i] != test1[i])
                {
                    areEqual = false;
                    count++;
                }
            }
        }

        Console.WriteLine("Are they equal?: " + areEqual.ToString() + ": " + count.ToString());

        Console.ReadLine();
    }

    private static byte[] ObjectToByteArray(Object obj)
    {
        if (obj == null)
            return null;
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }

修改 在我的应用程序中,我将有一个这样的类:

[Serializable]
class MetaDataModel
{
    private Dictionary<string, string> readers;
    private Dictionary<string, string> writers;
    public bool IsDirty { get; set; }
    public string PublicReaderKey { get; set; }
    public string CipherPrivateReaderKey { get; set; }
    public Dictionary<string, string> Readers
    {
        get
        {
            if (this.readers == null)
                this.readers = new Dictionary<string, string>();
            return this.readers;
        }
        set
        {
            this.readers = value;
        }
    }
    public string PublicWriterKey { get; set; }
    public string CipherPrivateWriterKey { get; set; }
    public Dictionary<string, string> Writers
    {
        get
        {
            if (this.writers == null)
                this.writers = new Dictionary<string, string>();
            return this.writers;
        }
        set
        {
            this.writers = value;
        }
    }
    public byte[] Signature { get; set; }
}

并希望它像这样使用:

MetaDataModel metaData = new MetaDataModel()

//filling the properties here

metaData.Signature = RSASignatureGenerator.HashAndSignData(this.ObjectToByteArray(metaData), this.rsaKeyPair[0]);

0 个答案:

没有答案