閱讀英文

共用方式為


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

取得 ICollection 物件,其中包含 IDictionary 物件的索引鍵。

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, 10
.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

另請參閱