KeyedCollectionとは? わかりやすく解説

KeyedCollection コンストラクタ ()

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

既定等値比較演算子使用する KeyedCollection クラス新しインスタンス初期化します。

名前空間: System.Collections.ObjectModel
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Dim instance As New KeyedCollection(Of
 TKey, TItem)
protected KeyedCollection ()
protected:
KeyedCollection ()
protected KeyedCollection ()
protected function KeyedCollection ()
解説解説

このコンストラクタ作成されKeyedCollection は、EqualityComparer.Default から取得するキーの型の既定ジェネリック等値比較演算子使用します異なジェネリック等値比較演算子指定するには、KeyedCollection(ジェネリック IEqualityComparer) コンストラクタまたは KeyedCollection(ジェネリック IEqualityComparer,Int32) コンストラクタ使用します

既定では、KeyedCollection には最初の項目の追加時に作成される検索ディクショナリが含まれます。高速検索可能にするため、KeyedCollection に項目が追加されると、項目のキー1 度だけ抽出され検索ディクショナリに保存されます。この動作は、KeyedCollection(ジェネリック IEqualityComparer,Int32) コンストラクタ使用し、ディクショナリ作成しきい値指定することによりオーバーライドできます

メモメモ

KeyedCollection クラス抽象クラス (Visual Basic の場合MustInherit) なので、使用するためにはこのクラスから派生させる必要があります派生型コンストラクタで、適切な KeyedCollection コンストラクタ呼び出します。コンストラクタ内の等値比較演算子やディクショナリ作成しきい値のように機能公開する要はありません。

このコンストラクタは O(1) 操作です。

使用例使用例

このコード例は、KeyedCollection からコレクション クラス派生させるために必要な最小限コード示してます。GetKeyForItem メソッドオーバーライドし、基本クラス コンストラクタに処理を代行させるパブリック コンストラクタ用意してます。また、KeyedCollection クラスおよび Collection クラスから継承されプロパティおよびメソッド多数示してます。

SimpleOrder クラスは、OrderItem オブジェクト含んでいる非常に単純な発注リストです。各オブジェクトは行項目を順番表しますOrderItemキー変更できません。これは、KeyedCollection派生クラス使用する際に考慮する必要がある重要な事項です。変更可能なキー使用するコード例詳細については、ChangeItemKey のトピック参照してください

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class represents a very simple keyed list of OrderItems,
' inheriting most of its behavior from the KeyedCollection and 
' Collection classes. The immediate base class is the constructed
' type KeyedCollection(Of Integer, OrderItem). When you inherit
' from KeyedCollection, the second generic type argument is the 
' type that you want to store in the collection -- in this case
' OrderItem. The first generic argument is the type that you want
' to use as a key. Its values must be calculated from OrderItem; 
' in this case it is the Integer field PartNumber, so SimpleOrder
' inherits KeyedCollection(Of Integer, OrderItem).
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer,
 OrderItem)

    ' The parameterless constructor of the base class creates a 
    ' KeyedCollection with an internal dictionary. For this code 
    ' example, no other constructors are exposed.
    '
    Public Sub New()
        MyBase.New()
    End Sub
    
    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. The input parameter type is the 
    ' second generic type argument, in this case OrderItem, and 
    ' the return value type is the first generic type argument,
    ' in this case Integer.
    '
    Protected Overrides Function
 GetKeyForItem( _
        ByVal item As OrderItem) As
 Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

End Class

Public Class Demo
    
    Public Shared Sub Main()
 
        Dim weekly As New
 SimpleOrder()

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget",
 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket",
 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor",
 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear",
 175, 5.17))
        
        Display(weekly)
    
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}",
 _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description:
 {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)
        Display(weekly)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut",
 10, .5))
        Display(weekly)

        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key.
 
        ' The other overload comes from Collection(Of OrderItem), the
 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of
 OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description:
 {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank",
 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem),
 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}",
 _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)
        Display(weekly)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)
        Display(weekly)

    End Sub
    
    Private Shared Sub Display(ByVal
 order As SimpleOrder) 
        Console.WriteLine()
        For Each item As
 OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    Public ReadOnly PartNumber As
 Integer
    Public ReadOnly Description As
 String
    Public ReadOnly UnitPrice As
 Double
    
    Private _quantity As Integer
 = 0
    
    Public Sub New(ByVal
 partNumber As Integer, _
                   ByVal description As String,
 _
                   ByVal quantity As Integer,
 _
                   ByVal unitPrice As Double)
 
        Me.PartNumber = partNumber
        Me.Description = description
        Me.Quantity = quantity
        Me.UnitPrice = unitPrice
    End Sub 'New
    
    Public Property Quantity() As
 Integer 
        Get
            Return _quantity
        End Get
        Set
            If value < 0 Then
                Throw New ArgumentException("Quantity
 cannot be negative.")
            End If
            _quantity = value
        End Set
    End Property
        
    Public Overrides Function
 ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'Insert(2, New OrderItem(...))
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'111033401     10 Nut          at      .50 =       5.00
'110072684    175 Gear         at     5.17 =     904.75
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'
'IndexOf(temp): 2
'
'Remove(temp)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'RemoveAt(0)
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and 
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the 
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem; 
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public class SimpleOrder : KeyedCollection<int,
 OrderItem>
{
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed.
    //
    public SimpleOrder() : base() {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument,
    // in this case int.
    //
    protected override int GetKeyForItem(OrderItem
 item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }
}

public class Demo
{    
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget",
 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket",
 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor",
 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear",
 175, 5.17));
        
        Display(weekly);
    
        // The Contains method of KeyedCollection takes the key, 
        // type, in this case int.
        //
        Console.WriteLine("\nContains(101030411): {0}", 
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}", 
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, New OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut",
 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2].Description);
 
        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank",
 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem>
 
        // takes an OrderItem instead of a key
        // 
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);
        Display(weekly);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);
        Display(weekly);

    }
    
    private static void
 Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }
}

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public class OrderItem
{
    public readonly int PartNumber;
    public readonly string Description;
    public readonly double UnitPrice;
    
    private int _quantity = 0;
    
    public OrderItem(int partNumber, string
 description, 
        int quantity, double unitPrice)
    {
        this.PartNumber = partNumber;
        this.Description = description;
        this.Quantity = quantity;
        this.UnitPrice = unitPrice;
    } 
    
    public int Quantity    
    {
        get { return _quantity; }
        set
        {
            if (value<0)
                throw new ArgumentException("Quantity cannot
 be negative.");
            
            _quantity = value;
        }
    }
        
    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;
    
public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
    
    OrderItem(int partNumber, String^ description, 
        int quantity, double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    } 
    
    property int Quantity    
    {
        int get() { return
 _quantity; }
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        }
    }
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
};

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and 
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the 
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem; 
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public ref class SimpleOrder : KeyedCollection<int,
 OrderItem^>
{
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed.
    //
public:
    SimpleOrder() {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument,
    // in this case int.
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override 
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));
        
        Display(weekly);
    
        // The Contains method of KeyedCollection takes the key, 
        // type, in this case int.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console::WriteLine("\nweekly(101030411)->Description: {0}",
 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, New OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem>
 
        // takes an OrderItem instead of a key
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);
        Display(weekly);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);
        Display(weekly);

    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order
 )
        {
            Console::WriteLine(item);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly(101030411)->Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly(2)->Description: Nut

coweekly[2] = gcnew OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
KeyedCollection ジェネリック クラス
KeyedCollection メンバ
System.Collections.ObjectModel 名前空間
IEqualityComparer ジェネリック インターフェイス

KeyedCollection コンストラクタ


KeyedCollection コンストラクタ (ジェネリック IEqualityComparer)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

指定した等値比較演算子使用する KeyedCollection クラス新しインスタンス初期化します。

名前空間: System.Collections.ObjectModel
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Protected Sub New ( _
    comparer As IEqualityComparer(Of TKey)
 _
)
Dim comparer As IEqualityComparer(Of
 TKey)

Dim instance As New KeyedCollection(Of
 TKey, TItem)(comparer)
protected KeyedCollection (
    IEqualityComparer<TKey> comparer
)
protected:
KeyedCollection (
    IEqualityComparer<TKey>^ comparer
)
protected KeyedCollection (
    IEqualityComparer<TKey> comparer
)
protected function KeyedCollection (
    comparer : IEqualityComparer<TKey>
)

パラメータ

comparer

キー比較する場合使用する IEqualityComparer ジェネリック インターフェイス実装。または、EqualityComparer.Default から取得するキーの型の既定等値比較演算子使用する場合null 参照 (Visual Basic では Nothing)。

解説解説

既定では、KeyedCollection には最初の項目の追加時に作成される検索ディクショナリが含まれます。高速検索可能にするため、KeyedCollection に項目が追加されると、項目のキー1 度だけ抽出され検索ディクショナリに保存されます。この動作は、KeyedCollection(ジェネリック IEqualityComparer,Int32) コンストラクタ使用し、ディクショナリ作成しきい値指定することによりオーバーライドできます

メモメモ

KeyedCollection クラス抽象クラス (Visual Basic の場合MustInherit) なので、使用するためにはこのクラスから派生させる必要があります派生型コンストラクタで、適切な KeyedCollection コンストラクタ呼び出します。コンストラクタ内の等値比較演算子やディクショナリ作成しきい値のように機能公開する要はありません。

このコンストラクタは O(1) 操作です。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
KeyedCollection ジェネリック クラス
KeyedCollection メンバ
System.Collections.ObjectModel 名前空間
IEqualityComparer ジェネリック インターフェイス

KeyedCollection コンストラクタ (ジェネリック IEqualityComparer, Int32)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

指定した等値比較演算子使用し指定したしきい値超えた場合検索ディクショナリを作成する、KeyedCollection クラス新しインスタンス初期化します。

名前空間: System.Collections.ObjectModel
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Protected Sub New ( _
    comparer As IEqualityComparer(Of TKey),
 _
    dictionaryCreationThreshold As Integer
 _
)
Dim comparer As IEqualityComparer(Of
 TKey)
Dim dictionaryCreationThreshold As Integer

Dim instance As New KeyedCollection(Of
 TKey, TItem)(comparer, dictionaryCreationThreshold)
protected KeyedCollection (
    IEqualityComparer<TKey> comparer,
    int dictionaryCreationThreshold
)
protected:
KeyedCollection (
    IEqualityComparer<TKey>^ comparer, 
    int dictionaryCreationThreshold
)
protected KeyedCollection (
    IEqualityComparer<TKey> comparer, 
    int dictionaryCreationThreshold
)
protected function KeyedCollection (
    comparer : IEqualityComparer<TKey>, 
    dictionaryCreationThreshold : int
)

パラメータ

comparer

キー比較する場合使用する IEqualityComparer ジェネリック インターフェイス実装。または、EqualityComparer.Default から取得するキーの型の既定等値比較演算子使用する場合null 参照 (Visual Basic では Nothing)。

dictionaryCreationThreshold

検索ディクショナリを作成せずにコレクション保有できる要素数 (0 を指定する最初の項目の追加時に検索ディクショナリが作成される)。検索ディクショナリを作成しない場合は -1。

例外例外
例外種類条件

ArgumentOutOfRangeException

dictionaryCreationThreshold が –1 未満です。

解説解説

既定では、KeyedCollection には最初の項目の追加時に作成される検索ディクショナリが含まれます。高速検索可能にするため、KeyedCollection に項目が追加されると、項目のキー1 度だけ抽出され検索ディクショナリに保存されます。このコンストラクタでは動作オーバーライドできます。0 を指定すると、最初要素追加時にディクショナリが作成され、1 を指定する2 番目の要素追加時にディクショナリが作成されます。以降も同様ですしきい値として –1 を指定した場合検索ディクショナリは作成されません。

非常に小さコレクション場合検索ディクショナリによって実現する検索速度の向上効果が、ディクショナリによる必要メモリ量の増加見合わない可能性ありますしきい値設定することにより、このトレードオフについて判断切り替える境界決定できます

メモメモ

KeyedCollection クラス抽象クラス (Visual Basic の場合MustInherit) なので、使用するためにはこのクラスから派生させる必要があります派生型コンストラクタで、適切な KeyedCollection コンストラクタ呼び出します。コンストラクタ内の等値比較演算子やディクショナリ作成しきい値のように機能公開する要はありません。

このコンストラクタは O(1) 操作です。

使用例使用例

このコード例では、InsertItem、RemoveItem、ClearItems、および SetItem の各プロテクト メソッドオーバーライドする方法示しAddRemove、および Clear の各メソッドカスタム動作と、既定Item プロパティ (C# の場合インデクサ) を設定するためのカスタム動作提供します。この例で提供されるカスタム動作は、Changed という名前の通知イベントです。これは、オーバーライドされた各メソッド最後発生します

このコード例では、しきい値を 0 に設定して KeyedCollection(ジェネリック IEqualityComparer,Int32) コンストラクタ使用するため、オブジェクトコレクション最初に追加されたときに内部ディクショナリが作成されます。

このコード例では、SimpleOrder クラス作成します。このクラスは、KeyedCollection から派生し単純な注文フォーム表してます。この注文フォームには、注文する項目を表す OrderItem オブジェクト含まれています。また、イベント情報や、変更種類識別する列挙含めるために、SimpleOrderChangedEventArgs クラス作成します

Demo クラスMain メソッドで、派生クラスプロパティおよびメソッド呼び出すことにより、カスタム動作の例を示します

このコード例では、変更できないキーを持つオブジェクト使用します変更可能なキー使用するコード例詳細については、ChangeItemKey のトピック参照してください

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class derives from KeyedCollection and shows how to override
' the protected ClearItems, InsertItem, RemoveItem, and SetItem 
' methods in order to change the behavior of the default Item 
' property and the Add, Clear, Insert, and Remove methods. The
' class implements a Changed event, which is raised by all the
' protected methods.
'
' SimpleOrder is a collection of OrderItem objects, and its key
' is the PartNumber field of OrderItem. PartNumber is an Integer,
' so SimpleOrder inherits KeyedCollection(Of Integer, OrderItem).
' (Note that the key of OrderItem cannot be changed; if it could 
' be changed, SimpleOrder would have to override ChangeItemKey.)
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer,
 OrderItem)

    Public Event Changed As
 EventHandler(Of SimpleOrderChangedEventArgs)

    ' This parameterless constructor calls the base class constructor
    ' that specifies a dictionary threshold of 0, so that the internal
    ' dictionary is created as soon as an item is added to the 
    ' collection.
    '
    Public Sub New()
        MyBase.New(Nothing, 0)
    End Sub
    
    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. 
    '
    Protected Overrides Function
 GetKeyForItem( _
        ByVal item As OrderItem) As
 Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

    Protected Overrides Sub
 InsertItem( _
        ByVal index As Integer,
 ByVal newItem As OrderItem)

        MyBase.InsertItem(index, newItem)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Added, newItem, Nothing))
    End Sub

    Protected Overrides Sub
 SetItem(ByVal index As Integer,
 _
        ByVal newItem As OrderItem)

        Dim replaced As OrderItem = Items(index)
        MyBase.SetItem(index, newItem)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Replaced, replaced, newItem))
    End Sub

    Protected Overrides Sub
 RemoveItem(ByVal index As Integer)

        Dim removedItem As OrderItem = Items(index)
        MyBase.RemoveItem(index)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Removed, removedItem, Nothing))
    End Sub

    Protected Overrides Sub
 ClearItems()
        MyBase.ClearItems()

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Cleared, Nothing, Nothing))
    End Sub

End Class

' Event argument for the Changed event.
'
Public Class SimpleOrderChangedEventArgs
    Inherits EventArgs

    Private _changedItem As OrderItem
    Private _changeType As ChangeType
    Private _replacedWith As OrderItem

    Public ReadOnly Property
 ChangedItem As OrderItem
        Get
            Return _changedItem
        End Get
    End Property

    Public ReadOnly Property
 ChangeType As ChangeType
        Get
            Return _changeType
        End Get
    End Property

    Public ReadOnly Property
 ReplacedWith As OrderItem
        Get
            Return _replacedWith
        End Get
    End Property

    Public Sub New(ByVal
 change As ChangeType, ByVal item As
 OrderItem, _
        ByVal replacement As OrderItem)

        _changeType = change
        _changedItem = item
        _replacedWith = replacement
    End Sub
End Class

Public Enum ChangeType
    Added
    Removed
    Replaced
    Cleared
End Enum

Public Class Demo
    
    Public Shared Sub Main()
 
        Dim weekly As New
 SimpleOrder()
        AddHandler weekly.Changed, AddressOf
 ChangedHandler

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget",
 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket",
 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor",
 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear",
 175, 5.17))

        Display(weekly)
        
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}",
 _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer. The property is read-only.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description:
 {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut",
 10, .5))
         
        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key.
 
        ' The other overload comes from Collection(Of OrderItem), the
 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of
 OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description:
 {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank",
 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem),
 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}",
 _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)

        ' Increase the quantity for a line item.
        Console.WriteLine(vbLf & "coweekly(1) = New OrderItem(...)")
        coweekly(1) = New OrderItem(coweekly(1).PartNumber, _
            coweekly(1).Description, coweekly(1).Quantity + 1000, _
            coweekly(1).UnitPrice)

        Display(weekly)

        Console.WriteLine()
        weekly.Clear()
    End Sub
    
    Private Shared Sub Display(ByVal
 order As SimpleOrder) 
        Console.WriteLine()
        For Each item As
 OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub

    Private Shared Sub ChangedHandler(ByVal
 source As Object, _
        ByVal e As SimpleOrderChangedEventArgs)

        Dim item As OrderItem = e.ChangedItem

        If e.ChangeType = ChangeType.Replaced Then
            Dim replacement As OrderItem =
 e.ReplacedWith

            Console.WriteLine("{0} (quantity {1}) was replaced
 " & _
                "by {2}, (quantity {3}).", item.Description,
 _
                item.Quantity, replacement.Description, replacement.Quantity)

        ElseIf e.ChangeType = ChangeType.Cleared Then
            Console.WriteLine("The order list was cleared.")

        Else
            Console.WriteLine("{0} (quantity {1}) was {2}.",
 _
                item.Description, item.Quantity, e.ChangeType)
        End If
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    
    Private _partNumber As Integer
    Private _description As String
    Private _unitPrice As Double
    Private _quantity As Integer

    Public ReadOnly Property
 PartNumber As Integer
        Get
            Return _partNumber
        End Get
    End Property

    Public ReadOnly Property
 Description As String
        Get
            Return _description
        End Get
    End Property

    Public ReadOnly Property
 UnitPrice As Double
        Get
            Return _unitPrice
        End Get
    End Property
    
    Public ReadOnly Property
 Quantity() As Integer 
        Get
            Return _quantity
        End Get
    End Property
    
    Public Sub New(ByVal
 partNumber As Integer, _
                   ByVal description As String,
 _
                   ByVal quantity As Integer,
 _
                   ByVal unitPrice As Double)
 
        _partNumber = partNumber
        _description = description
        _quantity = quantity
        _unitPrice = unitPrice
    End Sub 'New
        
    Public Overrides Function
 ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'Widget (quantity 400) was Added.
'Sprocket (quantity 27) was Added.
'Motor (quantity 10) was Added.
'Gear (quantity 175) was Added.
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'Motor (quantity 10) was Removed.
'
'Insert(2, New OrderItem(...))
'Nut (quantity 10) was Added.
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'Nut (quantity 10) was replaced by Crank, (quantity 27).
'
'IndexOf(temp): 2
'
'Remove(temp)
'Crank (quantity 27) was Removed.
'
'RemoveAt(0)
'Widget (quantity 400) was Removed.
'
'coweekly(1) = New OrderItem(...)
'Gear (quantity 175) was replaced by Gear, (quantity 1175).
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684   1175 Gear         at     5.17 =   6,074.75
'
'The order list was cleared.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem 
// methods in order to change the behavior of the default Item 
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem. PartNumber is an Integer,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could 
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public class SimpleOrder : KeyedCollection<int,
 OrderItem>
{
    public event EventHandler<SimpleOrderChangedEventArgs>
 Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the 
    // collection.
    //
    public SimpleOrder() : base(null,
 0) {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. 
    //
    protected override int GetKeyForItem(OrderItem
 item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }

    protected override void InsertItem(int
 index, OrderItem newItem)
    {
        base.InsertItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Added, newItem, null));
        }
    }

    protected override void SetItem(int
 index, OrderItem newItem)
    {
        OrderItem replaced = Items[index];
        base.SetItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Replaced, replaced, newItem));
        }
    }

    protected override void RemoveItem(int
 index)
    {
        OrderItem removedItem = Items[index];
        base.RemoveItem(index);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Removed, removedItem, null));
        }
    }

    protected override void ClearItems()
    {
        base.ClearItems();

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Cleared, null, null));
        }
    }
}

// Event argument for the Changed event.
//
public class SimpleOrderChangedEventArgs :
 EventArgs
{
    private OrderItem _changedItem;
    private ChangeType _changeType;
    private OrderItem _replacedWith;

    public OrderItem ChangedItem { get { return
 _changedItem; }}
    public ChangeType ChangeType { get { return
 _changeType; }}
    public OrderItem ReplacedWith { get { return
 _replacedWith; }}

    public SimpleOrderChangedEventArgs(ChangeType change, 
        OrderItem item, OrderItem replacement)
    {
        _changeType = change;
        _changedItem = item;
        _replacedWith = replacement;
    }
}

public enum ChangeType
{
    Added, 
    Removed, 
    Replaced, 
    Cleared
};

public class Demo
{    
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();
        weekly.Changed += new 
            EventHandler<SimpleOrderChangedEventArgs>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget",
 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket",
 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor",
 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear",
 175, 5.17));

        Display(weekly);
        
        // The Contains method of KeyedCollection takes TKey.
        //
        Console.WriteLine("\nContains(101030411): {0}", 
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}", 
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, new OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut",
 10, .5));
         
        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2].Description);
 
        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank",
 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>,
 
        // takes an OrderItem instead of a key.
        // 
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);

        // Increase the quantity for a line item.
        Console.WriteLine("\ncoweekly(1) = New OrderItem(...)");
        coweekly[1] = new OrderItem(coweekly[1].PartNumber, 
            coweekly[1].Description, coweekly[1].Quantity + 1000, 
            coweekly[1].UnitPrice);

        Display(weekly);

        Console.WriteLine();
        weekly.Clear();
    }
    
    private static void
 Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }

    private static void
 ChangedHandler(object source, 
        SimpleOrderChangedEventArgs e)
    {

        OrderItem item = e.ChangedItem;

        if (e.ChangeType==ChangeType.Replaced)
        {
            OrderItem replacement = e.ReplacedWith;

            Console.WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item.Description, 
                item.Quantity, replacement.Description, 
                replacement.Quantity);
        }
        else if(e.ChangeType == ChangeType.Cleared)
        {
            Console.WriteLine("The order list was cleared.");
        }
        else
        {
            Console.WriteLine("{0} (quantity {1}) was {2}.", 
                item.Description, item.Quantity, e.ChangeType);
        }
    }
}

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public class OrderItem
{
    private int _partNumber;
    private string _description;
    private double _unitPrice;
    private int _quantity;
    
    public int PartNumber { get
 { return _partNumber; }}
    public string Description { get
 { return _description; }}
    public double UnitPrice { get { return
 _unitPrice; }}
    public int Quantity { get
 { return _quantity; }}
    
    public OrderItem(int partNumber, string
 description, int quantity, 
        double unitPrice)
    {
        _partNumber = partNumber;
        _description = description;
        _quantity = quantity;
        _unitPrice = unitPrice;
    }
    
    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, new OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

coweekly(1) = New OrderItem(...)
Gear (quantity 175) was replaced by Gear, (quantity 1175).

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

public enum class ChangeTypes
{
    Added,
    Removed, 
    Replaced, 
    Cleared
};

ref class SimpleOrderChangedEventArgs; 

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;

public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
        
    OrderItem(int partNumber, String^ description, int
 quantity, 
        double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    };
    
    property int Quantity    
    {
        int get() { return
 _quantity; };
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        };
    };
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    };
};

// Event argument for the Changed event.
//
public ref class SimpleOrderChangedEventArgs
 : EventArgs
{
public:
    OrderItem^ ChangedItem;
    initonly ChangeTypes ChangeType;
    OrderItem^ ReplacedWith;

    SimpleOrderChangedEventArgs(ChangeTypes change, 
        OrderItem^ item, OrderItem^ replacement)
    {
        this->ChangeType = change;
        this->ChangedItem = item;
        this->ReplacedWith = replacement;
    }
};

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem 
// methods in order to change the behavior of the default Item 
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem-> PartNumber is an Integer
,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could 
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public ref class SimpleOrder : KeyedCollection<int,
 OrderItem^>
{
public:
    event EventHandler<SimpleOrderChangedEventArgs^>^ Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the 
    // collection.
    //
    SimpleOrder() : KeyedCollection<int, OrderItem^>(nullptr,
 0) {};
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. 
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }

    virtual void InsertItem(int index, OrderItem^
 newItem) override 
    {
        __super::InsertItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Added, newItem, nullptr));
    }

    virtual void SetItem(int index, OrderItem^
 newItem) override 
    {
        OrderItem^ replaced = this->Items[index];
        __super::SetItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Replaced, replaced, newItem));
    }

    virtual void RemoveItem(int index) override
 
    {
        OrderItem^ removedItem = Items[index];
        __super::RemoveItem(index);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Removed, removedItem, nullptr));
    }

    virtual void ClearItems() override 
    {
        __super::ClearItems();

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Cleared, nullptr, nullptr));
    }

    // This method uses the internal reference to the dictionary
    // to test fo
public:
    void AddOrMerge(OrderItem^ newItem)
    {

        int key = this->GetKeyForItem(newItem);
        OrderItem^ existingItem = nullptr;

        // The dictionary is not created until the first item is 
        // added, so it is necessary to test for null. Using 
        // AndAlso ensures that TryGetValue is not called if the
        // dictionary does not exist.
        //
        if (this->Dictionary != nullptr
 && 
            this->Dictionary->TryGetValue(key, existingItem))
        {
            existingItem->Quantity += newItem->Quantity;
        }
        else
        {
            this->Add(newItem);
        }
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();
        weekly->Changed += gcnew 
            EventHandler<SimpleOrderChangedEventArgs^>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem->
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));

        Display(weekly);
        
        // The Contains method of KeyedCollection takes TKey.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console::WriteLine("\nweekly[101030411]->Description: {0}",
 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, gcnew OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
         
        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>,
 
        // takes an OrderItem instead of a key.
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem->
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);

        weekly->AddOrMerge(gcnew OrderItem(110072684, "Gear", 1000,
 5.17));

        Display(weekly);

        Console::WriteLine();
        weekly->Clear();
    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order
 )
        {
            Console::WriteLine(item);
        }
    }

    static void ChangedHandler(Object^ source,
 
        SimpleOrderChangedEventArgs^ e)
    {
        OrderItem^ item = e->ChangedItem;

        if (e->ChangeType == ChangeTypes::Replaced)
        {
            OrderItem^ replacement = e->ReplacedWith;

            Console::WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item->Description, 
                item->Quantity, replacement->Description, 
                replacement->Quantity);
        }
        else if(e->ChangeType == ChangeTypes::Cleared)
        {
            Console::WriteLine("The order list was cleared.");
        }
        else
        {
            Console::WriteLine("{0} (quantity {1}) was {2}.", 
                item->Description, item->Quantity, e->ChangeType);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411]->Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, gcnew OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = gcnew OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
KeyedCollection ジェネリック クラス
KeyedCollection メンバ
System.Collections.ObjectModel 名前空間
IEqualityComparer ジェネリック インターフェイス

KeyedCollection ジェネリック クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

キーが値に埋め込まれているコレクション抽象基本クラス提供します

名前空間: System.Collections.ObjectModel
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public MustInherit Class
 KeyedCollection(Of TKey, TItem)
    Inherits Collection(Of TItem)
Dim instance As KeyedCollection(Of
 TKey, TItem)
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public abstract class KeyedCollection<TKey,TItem>
 : Collection<TItem>
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename TKey, typename TItem>
public ref class KeyedCollection abstract :
 public Collection<TItem>
J# では、ジェネリックな型およびメソッド使用できますが、新規に宣言することはできません。
JScript では、ジェネリックな型およびメソッド使用できません。

型パラメータ

TKey

コレクション内のキーの型。

TItem

コレクション内の項目の型。

解説解説

KeyedCollection クラスでは、O(1) のインデックスによる取得と、O(1) に近いキーによる取得両方使用できます。これは抽象型 (Visual Basic の場合MustInherit) ですが、このクラス構築ジェネリック型それぞれ抽象基本クラスとなるため、より正確には、無数にある抽象型集合ということできますKeyedCollection使用するには、適切な構築型からコレクション型を派生させます

KeyedCollection クラスは、IList ジェネリック インターフェイス基づいたコレクションと IDictionary ジェネリック インターフェイス基づいたコレクション両方特性備えてます。IList ジェネリック インターフェイス基づいたコレクション同様にKeyedCollection も、項目のインデックス付けされたリストです。IDictionary ジェネリック インターフェイス基づいたコレクション同様にKeyedCollection にも各要素関連付けられたキーあります

ディクショナリと異なりKeyedCollection要素キー/値ペアではなく、この場合は、要素全体が値であり、キーはその値内に埋め込まれています。たとえば、KeyedCollection<String,String> (Visual Basic の場合KeyedCollection(Of String, String)) から派生したコレクションに "John Doe Jr." という要素があるとき、この要素の値が "John Doe Jr."、キーが "Doe" であるよう場合考えられます。また、整数キーを含む従業員レコードコレクションKeyedCollection<int,Employee> から派生させることもできます抽象メソッド GetKeyForItem (Visual Basic の場合MustOverride) は、キー要素から抽出します。

既定では、KeyedCollection には検索ディクショナリが含まれます。高速検索可能にするため、KeyedCollection に項目が追加されると、項目のキー1 度だけ抽出され検索ディクショナリに保存されます。KeyedCollection作成する場合、この動作は、ディクショナリ作成しきい値指定することによりオーバーライドできます検索ディクショナリは、要素の数が最初にそのしきい値超えたときに作成されます。しきい値として –1 を指定した場合検索ディクショナリは作成されません。既定のディクショナリ作成しきい値ゼロ (0) です。

メモメモ

内部検索ディクショナリを使用する場合、このディクショナリには、TItem参照型のときはコレクションすべての項目への参照含まれTItem値型のときはコレクションすべての項目のコピー含まれます。たがってTItem値型のときに検索ディクショナリを使用するのは適切ではありません。

KeyedCollection 内のすべてのキー一意である必要がありますキーには null 参照 (Visual Basic では Nothing) は使用できません。

使用例使用例

このセクションには、2 つコード例含まれています。最初の例は、KeyedCollection から派生させるための必要最小限コードであり、多数メソッド継承してます。2 番目の例は、KeyedCollectionプロテクト メソッドオーバーライドしてカスタム動作提供する方法示してます。

例 1

このコード例は、KeyedCollection からコレクション クラス派生させるために必要な最小限コード示してます。GetKeyForItem メソッドオーバーライドし、基本クラス コンストラクタに処理を代行させるパブリック コンストラクタ用意してます。また、KeyedCollection クラスおよび Collection クラスから継承されプロパティおよびメソッド多数示してます。

SimpleOrder クラスは、OrderItem オブジェクト含んでいる非常に単純な発注リストです。各オブジェクトは行項目を順番表しますOrderItemキー変更できません。これは、KeyedCollection派生クラス使用する際に考慮する必要がある重要な事項です。変更可能なキー使用するコード例詳細については、ChangeItemKey のトピック参照してください

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class represents a very simple keyed list of OrderItems,
' inheriting most of its behavior from the KeyedCollection and 
' Collection classes. The immediate base class is the constructed
' type KeyedCollection(Of Integer, OrderItem). When you inherit
' from KeyedCollection, the second generic type argument is the 
' type that you want to store in the collection -- in this case
' OrderItem. The first generic argument is the type that you want
' to use as a key. Its values must be calculated from OrderItem; 
' in this case it is the Integer field PartNumber, so SimpleOrder
' inherits KeyedCollection(Of Integer, OrderItem).
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer,
 OrderItem)

    ' The parameterless constructor of the base class creates a 
    ' KeyedCollection with an internal dictionary. For this code 
    ' example, no other constructors are exposed.
    '
    Public Sub New()
        MyBase.New()
    End Sub
    
    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. The input parameter type is the 
    ' second generic type argument, in this case OrderItem, and 
    ' the return value type is the first generic type argument,
    ' in this case Integer.
    '
    Protected Overrides Function
 GetKeyForItem( _
        ByVal item As OrderItem) As
 Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

End Class

Public Class Demo
    
    Public Shared Sub Main()
 
        Dim weekly As New
 SimpleOrder()

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget",
 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket",
 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor",
 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear",
 175, 5.17))
        
        Display(weekly)
    
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}",
 _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description:
 {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)
        Display(weekly)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut",
 10, .5))
        Display(weekly)

        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key.
 
        ' The other overload comes from Collection(Of OrderItem), the
 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of
 OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description:
 {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank",
 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem),
 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}",
 _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)
        Display(weekly)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)
        Display(weekly)

    End Sub
    
    Private Shared Sub Display(ByVal
 order As SimpleOrder) 
        Console.WriteLine()
        For Each item As
 OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    Public ReadOnly PartNumber As
 Integer
    Public ReadOnly Description As
 String
    Public ReadOnly UnitPrice As
 Double
    
    Private _quantity As Integer
 = 0
    
    Public Sub New(ByVal
 partNumber As Integer, _
                   ByVal description As String,
 _
                   ByVal quantity As Integer,
 _
                   ByVal unitPrice As Double)
 
        Me.PartNumber = partNumber
        Me.Description = description
        Me.Quantity = quantity
        Me.UnitPrice = unitPrice
    End Sub 'New
    
    Public Property Quantity() As
 Integer 
        Get
            Return _quantity
        End Get
        Set
            If value < 0 Then
                Throw New ArgumentException("Quantity
 cannot be negative.")
            End If
            _quantity = value
        End Set
    End Property
        
    Public Overrides Function
 ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'Insert(2, New OrderItem(...))
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'111033401     10 Nut          at      .50 =       5.00
'110072684    175 Gear         at     5.17 =     904.75
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'
'IndexOf(temp): 2
'
'Remove(temp)
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
'
'RemoveAt(0)
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684    175 Gear         at     5.17 =     904.75
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and 
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the 
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem; 
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public class SimpleOrder : KeyedCollection<int,
 OrderItem>
{
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed.
    //
    public SimpleOrder() : base() {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument,
    // in this case int.
    //
    protected override int GetKeyForItem(OrderItem
 item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }
}

public class Demo
{    
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget",
 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket",
 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor",
 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear",
 175, 5.17));
        
        Display(weekly);
    
        // The Contains method of KeyedCollection takes the key, 
        // type, in this case int.
        //
        Console.WriteLine("\nContains(101030411): {0}", 
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}", 
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, New OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut",
 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2].Description);
 
        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank",
 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem>
 
        // takes an OrderItem instead of a key
        // 
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);
        Display(weekly);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);
        Display(weekly);

    }
    
    private static void
 Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }
}

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public class OrderItem
{
    public readonly int PartNumber;
    public readonly string Description;
    public readonly double UnitPrice;
    
    private int _quantity = 0;
    
    public OrderItem(int partNumber, string
 description, 
        int quantity, double unitPrice)
    {
        this.PartNumber = partNumber;
        this.Description = description;
        this.Quantity = quantity;
        this.UnitPrice = unitPrice;
    } 
    
    public int Quantity    
    {
        get { return _quantity; }
        set
        {
            if (value<0)
                throw new ArgumentException("Quantity cannot
 be negative.");
            
            _quantity = value;
        }
    }
        
    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;
    
public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
    
    OrderItem(int partNumber, String^ description, 
        int quantity, double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    } 
    
    property int Quantity    
    {
        int get() { return
 _quantity; }
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        }
    }
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
};

// This class represents a very simple keyed list of OrderItems,
// inheriting most of its behavior from the KeyedCollection and 
// Collection classes. The immediate base class is the constructed
// type KeyedCollection<int, OrderItem>. When you inherit
// from KeyedCollection, the second generic type argument is the 
// type that you want to store in the collection -- in this case
// OrderItem. The first type argument is the type that you want
// to use as a key. Its values must be calculated from OrderItem; 
// in this case it is the int field PartNumber, so SimpleOrder
// inherits KeyedCollection<int, OrderItem>.
//
public ref class SimpleOrder : KeyedCollection<int,
 OrderItem^>
{
    // The parameterless constructor of the base class creates a 
    // KeyedCollection with an internal dictionary. For this code 
    // example, no other constructors are exposed.
    //
public:
    SimpleOrder() {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. The input parameter type is the 
    // second generic type argument, in this case OrderItem, and 
    // the return value type is the first generic type argument,
    // in this case int.
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override 
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));
        
        Display(weekly);
    
        // The Contains method of KeyedCollection takes the key, 
        // type, in this case int.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes a key.
        //
        Console::WriteLine("\nweekly(101030411)->Description: {0}",
 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);
        Display(weekly);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, New OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
        Display(weekly);

        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method inherited from Collection<OrderItem>
 
        // takes an OrderItem instead of a key
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);
        Display(weekly);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);
        Display(weekly);

    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order
 )
        {
            Console::WriteLine(item);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly(101030411)->Description: Motor

Remove(101030411)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

Insert(2, New OrderItem(...))

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
111033401     10 Nut          at      .50 =       5.00
110072684    175 Gear         at     5.17 =     904.75

coweekly(2)->Description: Nut

coweekly[2] = gcnew OrderItem(...)

IndexOf(temp): 2

Remove(temp)

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75

RemoveAt(0)

110072675     27 Sprocket     at     5.30 =     143.10
110072684    175 Gear         at     5.17 =     904.75
 */

例 2

このコード例では、InsertItem、RemoveItem、ClearItems、および SetItem の各プロテクト メソッドオーバーライドする方法示しAddRemove、および Clear の各メソッドカスタム動作と、既定Item プロパティ (C# の場合インデクサ) を設定するためのカスタム動作提供します。この例で提供されるカスタム動作は、Changed という名前の通知イベントです。これは、オーバーライドされた各メソッド最後発生します

このコード例では、SimpleOrder クラス作成します。このクラスは、KeyedCollection から派生し単純な注文フォーム表してます。この注文フォームには、注文する項目を表す OrderItem オブジェクト含まれています。また、イベント情報や、変更種類識別する列挙含めるために、SimpleOrderChangedEventArgs クラス作成します

Demo クラスMain メソッドで、派生クラスプロパティおよびメソッド呼び出すことにより、カスタム動作の例を示します

このコード例では、変更できないキーを持つオブジェクト使用します変更可能なキー使用するコード例詳細については、ChangeItemKeyトピック参照してください

Imports System
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class derives from KeyedCollection and shows how to override
' the protected ClearItems, InsertItem, RemoveItem, and SetItem 
' methods in order to change the behavior of the default Item 
' property and the Add, Clear, Insert, and Remove methods. The
' class implements a Changed event, which is raised by all the
' protected methods.
'
' SimpleOrder is a collection of OrderItem objects, and its key
' is the PartNumber field of OrderItem. PartNumber is an Integer,
' so SimpleOrder inherits KeyedCollection(Of Integer, OrderItem).
' (Note that the key of OrderItem cannot be changed; if it could 
' be changed, SimpleOrder would have to override ChangeItemKey.)
'
Public Class SimpleOrder
    Inherits KeyedCollection(Of Integer,
 OrderItem)

    Public Event Changed As
 EventHandler(Of SimpleOrderChangedEventArgs)

    ' This parameterless constructor calls the base class constructor
    ' that specifies a dictionary threshold of 0, so that the internal
    ' dictionary is created as soon as an item is added to the 
    ' collection.
    '
    Public Sub New()
        MyBase.New(Nothing, 0)
    End Sub
    
    ' This is the only method that absolutely must be overridden,
    ' because without it the KeyedCollection cannot extract the
    ' keys from the items. 
    '
    Protected Overrides Function
 GetKeyForItem( _
        ByVal item As OrderItem) As
 Integer

        ' In this example, the key is the part number.
        Return item.PartNumber   
    End Function

    Protected Overrides Sub
 InsertItem( _
        ByVal index As Integer,
 ByVal newItem As OrderItem)

        MyBase.InsertItem(index, newItem)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Added, newItem, Nothing))
    End Sub

    Protected Overrides Sub
 SetItem(ByVal index As Integer,
 _
        ByVal newItem As OrderItem)

        Dim replaced As OrderItem = Items(index)
        MyBase.SetItem(index, newItem)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Replaced, replaced, newItem))
    End Sub

    Protected Overrides Sub
 RemoveItem(ByVal index As Integer)

        Dim removedItem As OrderItem = Items(index)
        MyBase.RemoveItem(index)

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Removed, removedItem, Nothing))
    End Sub

    Protected Overrides Sub
 ClearItems()
        MyBase.ClearItems()

        RaiseEvent Changed(Me, New
 SimpleOrderChangedEventArgs( _
            ChangeType.Cleared, Nothing, Nothing))
    End Sub

End Class

' Event argument for the Changed event.
'
Public Class SimpleOrderChangedEventArgs
    Inherits EventArgs

    Private _changedItem As OrderItem
    Private _changeType As ChangeType
    Private _replacedWith As OrderItem

    Public ReadOnly Property
 ChangedItem As OrderItem
        Get
            Return _changedItem
        End Get
    End Property

    Public ReadOnly Property
 ChangeType As ChangeType
        Get
            Return _changeType
        End Get
    End Property

    Public ReadOnly Property
 ReplacedWith As OrderItem
        Get
            Return _replacedWith
        End Get
    End Property

    Public Sub New(ByVal
 change As ChangeType, ByVal item As
 OrderItem, _
        ByVal replacement As OrderItem)

        _changeType = change
        _changedItem = item
        _replacedWith = replacement
    End Sub
End Class

Public Enum ChangeType
    Added
    Removed
    Replaced
    Cleared
End Enum

Public Class Demo
    
    Public Shared Sub Main()
 
        Dim weekly As New
 SimpleOrder()
        AddHandler weekly.Changed, AddressOf
 ChangedHandler

        ' The Add method, inherited from Collection, takes OrderItem.
        '
        weekly.Add(New OrderItem(110072674, "Widget",
 400, 45.17))
        weekly.Add(New OrderItem(110072675, "Sprocket",
 27, 5.3))
        weekly.Add(New OrderItem(101030411, "Motor",
 10, 237.5))
        weekly.Add(New OrderItem(110072684, "Gear",
 175, 5.17))

        Display(weekly)
        
        ' The Contains method of KeyedCollection takes TKey.
        '
        Console.WriteLine(vbLf & "Contains(101030411): {0}",
 _
            weekly.Contains(101030411))

        ' The default Item property of KeyedCollection takes the key
        ' type, Integer. The property is read-only.
        '
        Console.WriteLine(vbLf & "weekly(101030411).Description:
 {0}", _
            weekly(101030411).Description)

        ' The Remove method of KeyedCollection takes a key.
        '
        Console.WriteLine(vbLf & "Remove(101030411)")
        weekly.Remove(101030411)

        ' The Insert method, inherited from Collection, takes an 
        ' index and an OrderItem.
        '
        Console.WriteLine(vbLf & "Insert(2, New OrderItem(...))")
        weekly.Insert(2, New OrderItem(111033401, "Nut",
 10, .5))
         
        ' The default Item property is overloaded. One overload comes
        ' from KeyedCollection(Of Integer, OrderItem); that overload
        ' is read-only, and takes Integer because it retrieves by key.
 
        ' The other overload comes from Collection(Of OrderItem), the
 
        ' base class of KeyedCollection(Of Integer, OrderItem); it 
        ' retrieves by index, so it also takes an Integer. The compiler
        ' uses the most-derived overload, from KeyedCollection, so the
        ' only way to access SimpleOrder by index is to cast it to
        ' Collection(Of OrderItem). Otherwise the index is interpreted
        ' as a key, and KeyNotFoundException is thrown.
        '
        Dim coweekly As Collection(Of
 OrderItem) = weekly
        Console.WriteLine(vbLf & "coweekly(2).Description:
 {0}", _
            coweekly(2).Description)
 
        Console.WriteLine(vbLf & "coweekly(2) = New OrderItem(...)")
        coweekly(2) = New OrderItem(127700026, "Crank",
 27, 5.98)

        Dim temp As OrderItem = coweekly(2)

        ' The IndexOf method, inherited from Collection(Of OrderItem),
 
        ' takes an OrderItem instead of a key.
        ' 
        Console.WriteLine(vbLf & "IndexOf(temp): {0}",
 _
            weekly.IndexOf(temp))

        ' The inherited Remove method also takes an OrderItem.
        '
        Console.WriteLine(vbLf & "Remove(temp)")
        weekly.Remove(temp)

        Console.WriteLine(vbLf & "RemoveAt(0)")
        weekly.RemoveAt(0)

        ' Increase the quantity for a line item.
        Console.WriteLine(vbLf & "coweekly(1) = New OrderItem(...)")
        coweekly(1) = New OrderItem(coweekly(1).PartNumber, _
            coweekly(1).Description, coweekly(1).Quantity + 1000, _
            coweekly(1).UnitPrice)

        Display(weekly)

        Console.WriteLine()
        weekly.Clear()
    End Sub
    
    Private Shared Sub Display(ByVal
 order As SimpleOrder) 
        Console.WriteLine()
        For Each item As
 OrderItem In  order
            Console.WriteLine(item)
        Next item
    End Sub

    Private Shared Sub ChangedHandler(ByVal
 source As Object, _
        ByVal e As SimpleOrderChangedEventArgs)

        Dim item As OrderItem = e.ChangedItem

        If e.ChangeType = ChangeType.Replaced Then
            Dim replacement As OrderItem =
 e.ReplacedWith

            Console.WriteLine("{0} (quantity {1}) was replaced
 " & _
                "by {2}, (quantity {3}).", item.Description,
 _
                item.Quantity, replacement.Description, replacement.Quantity)

        ElseIf e.ChangeType = ChangeType.Cleared Then
            Console.WriteLine("The order list was cleared.")

        Else
            Console.WriteLine("{0} (quantity {1}) was {2}.",
 _
                item.Description, item.Quantity, e.ChangeType)
        End If
    End Sub
End Class

' This class represents a simple line item in an order. All the 
' values are immutable except quantity.
' 
Public Class OrderItem
    
    Private _partNumber As Integer
    Private _description As String
    Private _unitPrice As Double
    Private _quantity As Integer

    Public ReadOnly Property
 PartNumber As Integer
        Get
            Return _partNumber
        End Get
    End Property

    Public ReadOnly Property
 Description As String
        Get
            Return _description
        End Get
    End Property

    Public ReadOnly Property
 UnitPrice As Double
        Get
            Return _unitPrice
        End Get
    End Property
    
    Public ReadOnly Property
 Quantity() As Integer 
        Get
            Return _quantity
        End Get
    End Property
    
    Public Sub New(ByVal
 partNumber As Integer, _
                   ByVal description As String,
 _
                   ByVal quantity As Integer,
 _
                   ByVal unitPrice As Double)
 
        _partNumber = partNumber
        _description = description
        _quantity = quantity
        _unitPrice = unitPrice
    End Sub 'New
        
    Public Overrides Function
 ToString() As String 
        Return String.Format( _
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 _
            PartNumber, _quantity, Description, UnitPrice, _
            UnitPrice * _quantity)
    End Function
End Class

' This code example produces the following output:
'
'Widget (quantity 400) was Added.
'Sprocket (quantity 27) was Added.
'Motor (quantity 10) was Added.
'Gear (quantity 175) was Added.
'
'110072674    400 Widget       at    45.17 =  18,068.00
'110072675     27 Sprocket     at     5.30 =     143.10
'101030411     10 Motor        at   237.50 =   2,375.00
'110072684    175 Gear         at     5.17 =     904.75
'
'Contains(101030411): True
'
'weekly(101030411).Description: Motor
'
'Remove(101030411)
'Motor (quantity 10) was Removed.
'
'Insert(2, New OrderItem(...))
'Nut (quantity 10) was Added.
'
'coweekly(2).Description: Nut
'
'coweekly(2) = New OrderItem(...)
'Nut (quantity 10) was replaced by Crank, (quantity 27).
'
'IndexOf(temp): 2
'
'Remove(temp)
'Crank (quantity 27) was Removed.
'
'RemoveAt(0)
'Widget (quantity 400) was Removed.
'
'coweekly(1) = New OrderItem(...)
'Gear (quantity 175) was replaced by Gear, (quantity 1175).
'
'110072675     27 Sprocket     at     5.30 =     143.10
'110072684   1175 Gear         at     5.17 =   6,074.75
'
'The order list was cleared.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem 
// methods in order to change the behavior of the default Item 
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem. PartNumber is an Integer,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could 
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public class SimpleOrder : KeyedCollection<int,
 OrderItem>
{
    public event EventHandler<SimpleOrderChangedEventArgs>
 Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the 
    // collection.
    //
    public SimpleOrder() : base(null,
 0) {}
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. 
    //
    protected override int GetKeyForItem(OrderItem
 item)
    {
        // In this example, the key is the part number.
        return item.PartNumber;
    }

    protected override void InsertItem(int
 index, OrderItem newItem)
    {
        base.InsertItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Added, newItem, null));
        }
    }

    protected override void SetItem(int
 index, OrderItem newItem)
    {
        OrderItem replaced = Items[index];
        base.SetItem(index, newItem);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Replaced, replaced, newItem));
        }
    }

    protected override void RemoveItem(int
 index)
    {
        OrderItem removedItem = Items[index];
        base.RemoveItem(index);

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Removed, removedItem, null));
        }
    }

    protected override void ClearItems()
    {
        base.ClearItems();

        EventHandler<SimpleOrderChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new SimpleOrderChangedEventArgs(
                ChangeType.Cleared, null, null));
        }
    }
}

// Event argument for the Changed event.
//
public class SimpleOrderChangedEventArgs :
 EventArgs
{
    private OrderItem _changedItem;
    private ChangeType _changeType;
    private OrderItem _replacedWith;

    public OrderItem ChangedItem { get { return
 _changedItem; }}
    public ChangeType ChangeType { get { return
 _changeType; }}
    public OrderItem ReplacedWith { get { return
 _replacedWith; }}

    public SimpleOrderChangedEventArgs(ChangeType change, 
        OrderItem item, OrderItem replacement)
    {
        _changeType = change;
        _changedItem = item;
        _replacedWith = replacement;
    }
}

public enum ChangeType
{
    Added, 
    Removed, 
    Replaced, 
    Cleared
};

public class Demo
{    
    public static void Main()
    {
        SimpleOrder weekly = new SimpleOrder();
        weekly.Changed += new 
            EventHandler<SimpleOrderChangedEventArgs>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem.
        //
        weekly.Add(new OrderItem(110072674, "Widget",
 400, 45.17));
        weekly.Add(new OrderItem(110072675, "Sprocket",
 27, 5.3));
        weekly.Add(new OrderItem(101030411, "Motor",
 10, 237.5));
        weekly.Add(new OrderItem(110072684, "Gear",
 175, 5.17));

        Display(weekly);
        
        // The Contains method of KeyedCollection takes TKey.
        //
        Console.WriteLine("\nContains(101030411): {0}", 
            weekly.Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console.WriteLine("\nweekly[101030411].Description: {0}", 
            weekly[101030411].Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console.WriteLine("\nRemove(101030411)");
        weekly.Remove(101030411);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console.WriteLine("\nInsert(2, new OrderItem(...))");
        weekly.Insert(2, new OrderItem(111033401, "Nut",
 10, .5));
         
        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem> coweekly = weekly;
        Console.WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2].Description);
 
        Console.WriteLine("\ncoweekly[2] = new OrderItem(...)");
        coweekly[2] = new OrderItem(127700026, "Crank",
 27, 5.98);

        OrderItem temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>,
 
        // takes an OrderItem instead of a key.
        // 
        Console.WriteLine("\nIndexOf(temp): {0}", weekly.IndexOf(temp));

        // The inherited Remove method also takes an OrderItem.
        //
        Console.WriteLine("\nRemove(temp)");
        weekly.Remove(temp);

        Console.WriteLine("\nRemoveAt(0)");
        weekly.RemoveAt(0);

        // Increase the quantity for a line item.
        Console.WriteLine("\ncoweekly(1) = New OrderItem(...)");
        coweekly[1] = new OrderItem(coweekly[1].PartNumber, 
            coweekly[1].Description, coweekly[1].Quantity + 1000, 
            coweekly[1].UnitPrice);

        Display(weekly);

        Console.WriteLine();
        weekly.Clear();
    }
    
    private static void
 Display(SimpleOrder order)
    {
        Console.WriteLine();
        foreach( OrderItem item in order )
        {
            Console.WriteLine(item);
        }
    }

    private static void
 ChangedHandler(object source, 
        SimpleOrderChangedEventArgs e)
    {

        OrderItem item = e.ChangedItem;

        if (e.ChangeType==ChangeType.Replaced)
        {
            OrderItem replacement = e.ReplacedWith;

            Console.WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item.Description, 
                item.Quantity, replacement.Description, 
                replacement.Quantity);
        }
        else if(e.ChangeType == ChangeType.Cleared)
        {
            Console.WriteLine("The order list was cleared.");
        }
        else
        {
            Console.WriteLine("{0} (quantity {1}) was {2}.", 
                item.Description, item.Quantity, e.ChangeType);
        }
    }
}

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public class OrderItem
{
    private int _partNumber;
    private string _description;
    private double _unitPrice;
    private int _quantity;
    
    public int PartNumber { get
 { return _partNumber; }}
    public string Description { get
 { return _description; }}
    public double UnitPrice { get { return
 _unitPrice; }}
    public int Quantity { get
 { return _quantity; }}
    
    public OrderItem(int partNumber, string
 description, int quantity, 
        double unitPrice)
    {
        _partNumber = partNumber;
        _description = description;
        _quantity = quantity;
        _unitPrice = unitPrice;
    }
    
    public override string ToString()
    {
        return String.Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    }
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411].Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, new OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = new OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

coweekly(1) = New OrderItem(...)
Gear (quantity 175) was replaced by Gear, (quantity 1175).

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;

public enum class ChangeTypes
{
    Added,
    Removed, 
    Replaced, 
    Cleared
};

ref class SimpleOrderChangedEventArgs; 

// This class represents a simple line item in an order. All the 
// values are immutable except quantity.
// 
public ref class OrderItem
{
private:
    int _quantity;

public:
    initonly int PartNumber;
    initonly String^ Description;
    initonly double UnitPrice;
        
    OrderItem(int partNumber, String^ description, int
 quantity, 
        double unitPrice)
    {
        this->PartNumber = partNumber;
        this->Description = description;
        this->Quantity = quantity;
        this->UnitPrice = unitPrice;
    };
    
    property int Quantity    
    {
        int get() { return
 _quantity; };
        void set(int value)
        {
            if (value < 0)
                throw gcnew ArgumentException("Quantity cannot be negative.");
            
            _quantity = value;
        };
    };
        
    virtual String^ ToString() override 
    {
        return String::Format(
            "{0,9} {1,6} {2,-12} at {3,8:#,###.00} = {4,10:###,###.00}",
 
            PartNumber, _quantity, Description, UnitPrice, 
            UnitPrice * _quantity);
    };
};

// Event argument for the Changed event.
//
public ref class SimpleOrderChangedEventArgs
 : EventArgs
{
public:
    OrderItem^ ChangedItem;
    initonly ChangeTypes ChangeType;
    OrderItem^ ReplacedWith;

    SimpleOrderChangedEventArgs(ChangeTypes change, 
        OrderItem^ item, OrderItem^ replacement)
    {
        this->ChangeType = change;
        this->ChangedItem = item;
        this->ReplacedWith = replacement;
    }
};

// This class derives from KeyedCollection and shows how to override
// the protected ClearItems, InsertItem, RemoveItem, and SetItem 
// methods in order to change the behavior of the default Item 
// property and the Add, Clear, Insert, and Remove methods. The
// class implements a Changed event, which is raised by all the
// protected methods.
//
// SimpleOrder is a collection of OrderItem objects, and its key
// is the PartNumber field of OrderItem-> PartNumber is an Integer
,
// so SimpleOrder inherits KeyedCollection<int, OrderItem>.
// (Note that the key of OrderItem cannot be changed; if it could 
// be changed, SimpleOrder would have to override ChangeItemKey.)
//
public ref class SimpleOrder : KeyedCollection<int,
 OrderItem^>
{
public:
    event EventHandler<SimpleOrderChangedEventArgs^>^ Changed;

    // This parameterless constructor calls the base class constructor
    // that specifies a dictionary threshold of 0, so that the internal
    // dictionary is created as soon as an item is added to the 
    // collection.
    //
    SimpleOrder() : KeyedCollection<int, OrderItem^>(nullptr,
 0) {};
    
    // This is the only method that absolutely must be overridden,
    // because without it the KeyedCollection cannot extract the
    // keys from the items. 
    //
protected:
    virtual int GetKeyForItem(OrderItem^ item) override
    {
        // In this example, the key is the part number.
        return item->PartNumber;
    }

    virtual void InsertItem(int index, OrderItem^
 newItem) override 
    {
        __super::InsertItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Added, newItem, nullptr));
    }

    virtual void SetItem(int index, OrderItem^
 newItem) override 
    {
        OrderItem^ replaced = this->Items[index];
        __super::SetItem(index, newItem);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Replaced, replaced, newItem));
    }

    virtual void RemoveItem(int index) override
 
    {
        OrderItem^ removedItem = Items[index];
        __super::RemoveItem(index);

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Removed, removedItem, nullptr));
    }

    virtual void ClearItems() override 
    {
        __super::ClearItems();

        Changed(this, gcnew SimpleOrderChangedEventArgs(
            ChangeTypes::Cleared, nullptr, nullptr));
    }

    // This method uses the internal reference to the dictionary
    // to test fo
public:
    void AddOrMerge(OrderItem^ newItem)
    {

        int key = this->GetKeyForItem(newItem);
        OrderItem^ existingItem = nullptr;

        // The dictionary is not created until the first item is 
        // added, so it is necessary to test for null. Using 
        // AndAlso ensures that TryGetValue is not called if the
        // dictionary does not exist.
        //
        if (this->Dictionary != nullptr
 && 
            this->Dictionary->TryGetValue(key, existingItem))
        {
            existingItem->Quantity += newItem->Quantity;
        }
        else
        {
            this->Add(newItem);
        }
    }
};

public ref class Demo
{    
public:
    static void Main()
    {
        SimpleOrder^ weekly = gcnew SimpleOrder();
        weekly->Changed += gcnew 
            EventHandler<SimpleOrderChangedEventArgs^>(ChangedHandler);

        // The Add method, inherited from Collection, takes OrderItem->
        //
        weekly->Add(gcnew OrderItem(110072674, "Widget", 400, 45.17));
        weekly->Add(gcnew OrderItem(110072675, "Sprocket", 27, 5.3));
        weekly->Add(gcnew OrderItem(101030411, "Motor", 10, 237.5));
        weekly->Add(gcnew OrderItem(110072684, "Gear", 175, 5.17));

        Display(weekly);
        
        // The Contains method of KeyedCollection takes TKey.
        //
        Console::WriteLine("\nContains(101030411): {0}", 
            weekly->Contains(101030411));

        // The default Item property of KeyedCollection takes the key
        // type, Integer. The property is read-only.
        //
        Console::WriteLine("\nweekly[101030411]->Description: {0}",
 
            weekly[101030411]->Description);

        // The Remove method of KeyedCollection takes a key.
        //
        Console::WriteLine("\nRemove(101030411)");
        weekly->Remove(101030411);

        // The Insert method, inherited from Collection, takes an 
        // index and an OrderItem.
        //
        Console::WriteLine("\nInsert(2, gcnew OrderItem(...))");
        weekly->Insert(2, gcnew OrderItem(111033401, "Nut", 10, .5));
         
        // The default Item property is overloaded. One overload comes
        // from KeyedCollection<int, OrderItem>; that overload
        // is read-only, and takes Integer because it retrieves by key.
 
        // The other overload comes from Collection<OrderItem>,
 the 
        // base class of KeyedCollection<int, OrderItem>; it 
        // retrieves by index, so it also takes an Integer. The compiler
        // uses the most-derived overload, from KeyedCollection, so
 the
        // only way to access SimpleOrder by index is to cast it to
        // Collection<OrderItem>. Otherwise the index is interpreted
        // as a key, and KeyNotFoundException is thrown.
        //
        Collection<OrderItem^>^ coweekly = weekly;
        Console::WriteLine("\ncoweekly[2].Description: {0}", 
            coweekly[2]->Description);
 
        Console::WriteLine("\ncoweekly[2] = gcnew OrderItem(...)");
        coweekly[2] = gcnew OrderItem(127700026, "Crank", 27, 5.98);

        OrderItem^ temp = coweekly[2];

        // The IndexOf method, inherited from Collection<OrderItem>,
 
        // takes an OrderItem instead of a key.
        // 
        Console::WriteLine("\nIndexOf(temp): {0}", weekly->IndexOf(temp));

        // The inherited Remove method also takes an OrderItem->
        //
        Console::WriteLine("\nRemove(temp)");
        weekly->Remove(temp);

        Console::WriteLine("\nRemoveAt(0)");
        weekly->RemoveAt(0);

        weekly->AddOrMerge(gcnew OrderItem(110072684, "Gear", 1000,
 5.17));

        Display(weekly);

        Console::WriteLine();
        weekly->Clear();
    }
    
private:
    static void Display(SimpleOrder^ order)
    {
        Console::WriteLine();
        for each( OrderItem^ item in order
 )
        {
            Console::WriteLine(item);
        }
    }

    static void ChangedHandler(Object^ source,
 
        SimpleOrderChangedEventArgs^ e)
    {
        OrderItem^ item = e->ChangedItem;

        if (e->ChangeType == ChangeTypes::Replaced)
        {
            OrderItem^ replacement = e->ReplacedWith;

            Console::WriteLine("{0} (quantity {1}) was replaced " +
                "by {2}, (quantity {3}).", item->Description, 
                item->Quantity, replacement->Description, 
                replacement->Quantity);
        }
        else if(e->ChangeType == ChangeTypes::Cleared)
        {
            Console::WriteLine("The order list was cleared.");
        }
        else
        {
            Console::WriteLine("{0} (quantity {1}) was {2}.", 
                item->Description, item->Quantity, e->ChangeType);
        }
    }
};

void main()
{
    Demo::Main();
}

/* This code example produces the following output:

Widget (quantity 400) was Added.
Sprocket (quantity 27) was Added.
Motor (quantity 10) was Added.
Gear (quantity 175) was Added.

110072674    400 Widget       at    45.17 =  18,068.00
110072675     27 Sprocket     at     5.30 =     143.10
101030411     10 Motor        at   237.50 =   2,375.00
110072684    175 Gear         at     5.17 =     904.75

Contains(101030411): True

weekly[101030411]->Description: Motor

Remove(101030411)
Motor (quantity 10) was Removed.

Insert(2, gcnew OrderItem(...))
Nut (quantity 10) was Added.

coweekly[2].Description: Nut

coweekly[2] = gcnew OrderItem(...)
Nut (quantity 10) was replaced by Crank, (quantity 27).

IndexOf(temp): 2

Remove(temp)
Crank (quantity 27) was Removed.

RemoveAt(0)
Widget (quantity 400) was Removed.

110072675     27 Sprocket     at     5.30 =     143.10
110072684   1175 Gear         at     5.17 =   6,074.75

The order list was cleared.
 */
継承階層継承階層
System.Object
   System.Collections.ObjectModel.Collection
    System.Collections.ObjectModel.KeyedCollection
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
KeyedCollection メンバ
System.Collections.ObjectModel 名前空間
StringDictionary

KeyedCollection プロパティ


KeyedCollection メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Add  Collection末尾オブジェクト追加します。 ( Collection から継承されます。)
パブリック メソッド Clear  Collection からすべての要素削除します。 ( Collection から継承されます。)
パブリック メソッド Contains 指定したキー要素コレクション含まれているかどうか確認します
パブリック メソッド CopyTo  Collection 全体互換性のある 1 次元Arrayコピーしますコピー操作は、コピー先の配列指定したインデックスから始まります。 ( Collection から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetEnumerator  Collection反復処理する列挙子を返します。 ( Collection から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド IndexOf  指定したオブジェクト検索しCollection 全体内で最初に見つかった位置の 0 から始まるインデックス返します。 ( Collection から継承されます。)
パブリック メソッド Insert  Collection 内の指定したインデックス位置要素挿入します。 ( Collection から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド Remove 指定したキー持つ要素を KeyedCollection から削除します
パブリック メソッド RemoveAt  Collection指定したインデックスにある要素削除します。 ( Collection から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

KeyedCollection ジェネリック クラス
System.Collections.ObjectModel 名前空間
StringDictionary

KeyedCollection メンバ

キーが値に埋め込まれているコレクション抽象基本クラス提供します

KeyedCollection ジェネリック型公開されるメンバを以下の表に示します


プロテクト コンストラクタプロテクト コンストラクタ
パブリック プロパティパブリック プロパティ
プロテクト プロパティプロテクト プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Add  Collection末尾オブジェクト追加します。 (Collection から継承されます。)
パブリック メソッド Clear  Collection からすべての要素削除します。 (Collection から継承されます。)
パブリック メソッド Contains 指定したキー要素コレクション含まれているかどうか確認します
パブリック メソッド CopyTo  Collection 全体互換性のある 1 次元Arrayコピーしますコピー操作は、コピー先の配列指定したインデックスから始まります。 (Collection から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetEnumerator  Collection反復処理する列挙子を返します。 (Collection から継承されます。)
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド IndexOf  指定したオブジェクト検索しCollection 全体内で最初に見つかった位置の 0 から始まるインデックス返します。 (Collection から継承されます。)
パブリック メソッド Insert  Collection 内の指定したインデックス位置要素挿入します。 (Collection から継承されます。)
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド Remove 指定したキー持つ要素を KeyedCollection から削除します
パブリック メソッド RemoveAt  Collection指定したインデックスにある要素削除します。 (Collection から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

KeyedCollection ジェネリック クラス
System.Collections.ObjectModel 名前空間
StringDictionary



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「KeyedCollection」の関連用語

KeyedCollectionのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



KeyedCollectionのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS