IDictionary 接口

定义

表示键/值对的非泛型集合。

C#
public interface IDictionary : System.Collections.ICollection
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IDictionary : System.Collections.ICollection
派生
属性
实现

示例

下面的代码示例演示如何定义实现 IDictionary 接口的简单字典类。

C#
using System;
using System.Collections;

// This class implements a simple dictionary using an array of DictionaryEntry objects (key/value pairs).
public class SimpleDictionary : IDictionary
{
    // The array of items
    private DictionaryEntry[] items;
    private Int32 ItemsInUse = 0;

    // Construct the SimpleDictionary with the desired number of items.
    // The number of items cannot change for the life time of this SimpleDictionary.
    public SimpleDictionary(Int32 numItems)
    {
        items = new DictionaryEntry[numItems];
    }

    #region IDictionary Members
    public bool IsReadOnly { get { return false; } }
    public bool Contains(object key)
    {
       Int32 index;
       return TryGetIndexOfKey(key, out index);
    }
    public bool IsFixedSize { get { return false; } }
    public void Remove(object key)
    {
        if (key == null) throw new ArgumentNullException("key");
        // Try to find the key in the DictionaryEntry array
        Int32 index;
        if (TryGetIndexOfKey(key, out index))
        {
            // If the key is found, slide all the items up.
            Array.Copy(items, index + 1, items, index, ItemsInUse - index - 1);
            ItemsInUse--;
        }
        else
        {
            // If the key is not in the dictionary, just return.
        }
    }
    public void Clear() { ItemsInUse = 0; }
    public void Add(object key, object value)
    {
        // Add the new key/value pair even if this key already exists in the dictionary.
        if (ItemsInUse == items.Length)
            throw new InvalidOperationException("The dictionary cannot hold any more items.");
        items[ItemsInUse++] = new DictionaryEntry(key, value);
    }
    public ICollection Keys
    {
        get
        {
            // Return an array where each item is a key.
            Object[] keys = new Object[ItemsInUse];
            for (Int32 n = 0; n < ItemsInUse; n++)
                keys[n] = items[n].Key;
            return keys;
        }
    }
    public ICollection Values
    {
        get
        {
            // Return an array where each item is a value.
            Object[] values = new Object[ItemsInUse];
            for (Int32 n = 0; n < ItemsInUse; n++)
                values[n] = items[n].Value;
            return values;
        }
    }
    public object this[object key]
    {
        get
        {
            // If this key is in the dictionary, return its value.
            Int32 index;
            if (TryGetIndexOfKey(key, out index))
            {
                // The key was found; return its value.
                return items[index].Value;
            }
            else
            {
                // The key was not found; return null.
                return null;
            }
        }

        set
        {
            // If this key is in the dictionary, change its value.
            Int32 index;
            if (TryGetIndexOfKey(key, out index))
            {
                // The key was found; change its value.
                items[index].Value = value;
            }
            else
            {
                // This key is not in the dictionary; add this key/value pair.
                Add(key, value);
            }
        }
    }
    private Boolean TryGetIndexOfKey(Object key, out Int32 index)
    {
        for (index = 0; index < ItemsInUse; index++)
        {
            // If the key is found, return true (the index is also returned).
            if (items[index].Key.Equals(key)) return true;
        }

        // Key not found, return false (index should be ignored by the caller).
        return false;
    }
    private class SimpleDictionaryEnumerator : IDictionaryEnumerator
    {
        // A copy of the SimpleDictionary object's key/value pairs.
        DictionaryEntry[] items;
        Int32 index = -1;

        public SimpleDictionaryEnumerator(SimpleDictionary sd)
        {
            // Make a copy of the dictionary entries currently in the SimpleDictionary object.
            items = new DictionaryEntry[sd.Count];
            Array.Copy(sd.items, 0, items, 0, sd.Count);
        }

        // Return the current item.
        public Object Current { get { ValidateIndex(); return items[index]; } }

        // Return the current dictionary entry.
        public DictionaryEntry Entry
        {
            get { return (DictionaryEntry) Current; }
        }

        // Return the key of the current item.
        public Object Key { get { ValidateIndex();  return items[index].Key; } }

        // Return the value of the current item.
        public Object Value { get { ValidateIndex();  return items[index].Value; } }

        // Advance to the next item.
        public Boolean MoveNext()
        {
            if (index < items.Length - 1) { index++; return true; }
            return false;
        }

        // Validate the enumeration index and throw an exception if the index is out of range.
        private void ValidateIndex()
        {
            if (index < 0 || index >= items.Length)
            throw new InvalidOperationException("Enumerator is before or after the collection.");
        }

        // Reset the index to restart the enumeration.
        public void Reset()
        {
            index = -1;
        }
    }
    public IDictionaryEnumerator GetEnumerator()
    {
        // Construct and return an enumerator.
        return new SimpleDictionaryEnumerator(this);
    }
    #endregion

    #region ICollection Members
    public bool IsSynchronized { get { return false; } }
    public object SyncRoot { get { throw new NotImplementedException(); } }
    public int Count { get { return ItemsInUse; } }
    public void CopyTo(Array array, int index) { throw new NotImplementedException(); }
    #endregion

    #region IEnumerable Members
    IEnumerator IEnumerable.GetEnumerator()
    {
        // Construct and return an enumerator.
        return ((IDictionary)this).GetEnumerator();
    }
    #endregion
}

public sealed class App
{
    static void Main()
    {
        // Create a dictionary that contains no more than three entries.
        IDictionary d = new SimpleDictionary(3);

        // Add three people and their ages to the dictionary.
        d.Add("Jeff", 40);
        d.Add("Kristin", 34);
        d.Add("Aidan", 1);

        Console.WriteLine("Number of elements in dictionary = {0}", d.Count);

        Console.WriteLine("Does dictionary contain 'Jeff'? {0}", d.Contains("Jeff"));
        Console.WriteLine("Jeff's age is {0}", d["Jeff"]);

        // Display every entry's key and value.
        foreach (DictionaryEntry de in d)
        {
            Console.WriteLine("{0} is {1} years old.", de.Key, de.Value);
        }

        // Remove an entry that exists.
        d.Remove("Jeff");

        // Remove an entry that does not exist, but do not throw an exception.
        d.Remove("Max");

        // Show the names (keys) of the people in the dictionary.
        foreach (String s in d.Keys)
            Console.WriteLine(s);

        // Show the ages (values) of the people in the dictionary.
        foreach (Int32 age in d.Values)
            Console.WriteLine(age);
    }
}

// This code produces the following output.
//
// Number of elements in dictionary = 3
// Does dictionary contain 'Jeff'? True
// Jeff's age is 40
// Jeff is 40 years old.
// Kristin is 34 years old.
// Aidan is 1 years old.
// Kristin
// Aidan
// 34
// 1

注解

IDictionary 接口是键/值对的非泛型集合的基本接口。 有关此接口的通用版本,请参阅 System.Collections.Generic.IDictionary<TKey,TValue>

每个元素都是存储在 DictionaryEntry 对象中的键/值对。

每个对必须具有唯一键。 实现因是否允许密钥为 null 而有所不同。 该值可以为 null,不必是唯一的。 IDictionary 接口允许枚举包含的键和值,但它并不表示任何特定的排序顺序。

IDictionary 实现分为三个类别:只读、固定大小、可变大小。 无法修改只读 IDictionary 对象。 固定大小的 IDictionary 对象不允许添加或删除元素,但允许修改现有元素。 可变大小的 IDictionary 对象允许添加、删除和修改元素。

C# 语言的 foreach 语句(在 Visual Basic 中For Each)返回集合中元素类型的对象。 由于 IDictionary 对象的每个元素都是键/值对,因此元素类型不是键的类型或值的类型。 而是 DictionaryEntry元素类型。 例如:

C#
foreach (DictionaryEntry de in myDictionary)
{
    //...
}

foreach 语句是枚举器周围的包装器,它只允许从集合中读取但不允许写入集合。

实施者说明

实现类必须具有比较键的方法。

属性

Count

获取 ICollection中包含的元素数。

(继承自 ICollection)
IsFixedSize

获取一个值,该值指示 IDictionary 对象是否具有固定大小。

IsReadOnly

获取一个值,该值指示 IDictionary 对象是否为只读。

IsSynchronized

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。

(继承自 ICollection)
Item[Object]

获取或设置具有指定键的元素。

Keys

获取包含 IDictionary 对象的键的 ICollection 对象。

SyncRoot

获取可用于同步对 ICollection的访问的对象。

(继承自 ICollection)
Values

获取一个 ICollection 对象,该对象包含 IDictionary 对象中的值。

方法

Add(Object, Object)

将具有提供的键和值的元素添加到 IDictionary 对象。

Clear()

IDictionary 对象中删除所有元素。

Contains(Object)

确定 IDictionary 对象是否包含具有指定键的元素。

CopyTo(Array, Int32)

从特定 Array 索引开始,将 ICollection 的元素复制到 Array

(继承自 ICollection)
GetEnumerator()

返回 IDictionary 对象的 IDictionaryEnumerator 对象。

Remove(Object)

IDictionary 对象中删除具有指定键的元素。

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定类型。

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。

AsParallel(IEnumerable)

启用查询的并行化。

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryable

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅