1. 程式人生 > >知識點總結: c#,使用自定義型別來作為Dictionary的Key

知識點總結: c#,使用自定義型別來作為Dictionary的Key

首先來看一個變數的定義:

/// <summary>
        /// key依次是StationId,channelId,deviceId,paraType,dataId,dataTypeId,logicalDeviceIndex,paraHandle,sourceId,value是paraName。讀取PC_TB_35_07表後,再找到相應的SourceId後,儲存到這裡.儲存的是定時記錄
        /// </summary>
        private
            Dictionary
                <uint,
                    Dictionary
                        <uint, Dictionary<uint, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, string>>>>>
                            >>>> m_PC_TB_35_07DatalogDic =
                                new Dictionary
                <uint,
                    Dictionary
                        <uint, Dictionary<uint, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, Dictionary<int, string>>>>>
                            >>>>();

看不懂吧?看起來很困難吧。其實就是因為key有多個欄位,但是寫程式碼的人並沒有想到可以使用使用自定義型別來作為key,所以就使用Dictionary套Dictionary的方式,這種方式會導致用的時候也很痛苦,例如,要一層一層的判斷,這樣就導致了每次使用,要做n次字典的查詢,我數了一下,HasDatalog的一次呼叫,會導致17次的字典查詢,實際上只需要一兩次就夠了。

public bool HasDatalog(uint stationId, uint channelId, uint deviceId)
        {
            if (!GetDatalogForChannel(stationId, channelId))
                return false;
            if (!m_PC_TB_35_07DatalogDic.ContainsKey(stationId))
                return false;
            if (!m_PC_TB_35_07DatalogDic[stationId].ContainsKey(channelId))
                return false;
            if (!m_PC_TB_35_07DatalogDic[stationId][channelId].ContainsKey(deviceId))
                return false;
            if (!m_PC_TB_35_07DatalogDic[stationId][channelId][deviceId].ContainsKey(1))
                return false;
            if (m_PC_TB_35_07DatalogDic[stationId][channelId][deviceId][1].Count == 0)
                return false;
            return true;            
        }

所以考慮使用自定義結構來作為Dictionary的Key,示例程式碼如下,其實主要就是要讓自定義型別實現IEqualityComparer介面,而這裡面最關鍵的就是要實現GetHashCode,好在這個結構的欄位不多,所以就參考一下《C#本質論(第三版)》p267的實現,大致的程式碼如下。


using System.Collections.Generic;

namespace TestDictionary
{
     struct DatalogValue
    {
        public int paraHandle;
        public int paraName;
    }

    struct DatalogKey : IEqualityComparer<DatalogKey>
    {
        public DatalogKey(uint dataId, uint dataTypeId, uint logicalDeviceIndex)
        {
            this.dataId = dataId;
            this.dataTypeId = dataTypeId;
            this.logicalDeviceIndex = logicalDeviceIndex;
        }

        public uint dataId;
        public uint dataTypeId;
        public uint logicalDeviceIndex;

        public bool Equals(DatalogKey x, DatalogKey y)
        {
            return x.dataId == y.dataId &&
                   x.dataTypeId == y.dataTypeId && 
                   x.logicalDeviceIndex == y.logicalDeviceIndex;
        }

        public int GetHashCode(DatalogKey obj)
        {
            int hashCode = dataId.GetHashCode();
            if (hashCode != dataTypeId.GetHashCode())            
                hashCode ^= dataTypeId.GetHashCode();                            
            if (hashCode != logicalDeviceIndex.GetHashCode())
                hashCode ^= dataTypeId.GetHashCode();
            return hashCode;
        }
    }
}

測試:


using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace TestDictionary
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<DatalogKey, int> testDataLog = new Dictionary<DatalogKey, int>();
            testDataLog.Add(new DatalogKey(1, 1, 1), 1);
            testDataLog.Add(new DatalogKey(1, 2, 1), 2);
            testDataLog.Add(new DatalogKey(1, 3, 1), 3);
            testDataLog.Add(new DatalogKey(2, 1, 1), 4);
            testDataLog.Add(new DatalogKey(2, 2, 1), 4);
            MessageBox.Show(testDataLog[new DatalogKey(2, 1, 1)].ToString());

            if(!testDataLog.ContainsKey(new DatalogKey(2,1,2)))
                MessageBox.Show("no");

        }
    }
}