2016年8月22日月曜日

型を指定するHashtable

C#にはHashtable(連想配列)があって、コレを使い時があるけど、HashtableはKeyもValueもObject型なので使い勝手が悪い。ということでKeyとValueの型をそれぞれ指定できるラッパーを作ってみた。
一部のメソッド等は実装しただけで動作確認していないので動かなかったらごめんなさい。例外とかもちゃんと作ってないです。
連想配列とか使いたくなるとJSとか便利だなーとか思ったり。

追記:2016/08/29
.NetFW4以降ならConcurrentDictionaryを使いましょう。こいつならKetとValueの型を指定し、スレッドセーフでアクセスすることができます。


class HashList<ValueType, KeyType>
{
    private Hashtable table_;

    public HashList()
    {
        table_ = new Hashtable();
    }

    public bool ContainsKey(KeyType key)
    {
        return (table_.ContainsKey(key));
    }

    public ValueType[] ToArray()
    {
        List<ValueType> list = new List<ValueType>();

        foreach (ValueType v in table_.Values)
        {
            if (v.GetType() == typeof(ValueType))
            { list.Add((ValueType)v); }
        }

        return (list.ToArray());
    }

    public void Clear()
    {
        table_.Clear();
    }

    public void Remove(KeyType key)
    {
        table_.Remove(key);
    }

    public ValueType this[KeyType key]
    {
        get
        {
            if (!ContainsKey(key))
            { throw (new KeyNotFoundException()); }

            object obj = table_[key];

            if (obj.GetType() != typeof(ValueType))
            { throw (new KeyNotFoundException()); }

            return ((ValueType)obj);
        }
        set
        {
            table_[key] = value;
        }
    }

    public int Count
    {
        get
        {
            return (table_.Count);
        }
    }

    public KeyType[] Keys
    {
        get
        {
            List<KeyType> list = new List<KeyType>();

            foreach (object obj in table_.Keys)
            {
                if (obj.GetType() != typeof(KeyType))
                { continue; }

                list.Add((KeyType)obj);
            }

            return (list.ToArray());
        }
    }

    public ValueType[] Values
    {
        get
        {
            List<ValueType> list = new List<ValueType>();

            foreach (object obj in table_.Values)
            {
                if (obj.GetType() != typeof(ValueType))
                { continue; }

                list.Add((ValueType)obj);
            }

            return (list.ToArray());
        }
    }
}

0 件のコメント:

コメントを投稿