KeyedCollection<TKey,TItem>.ChangeItemKey(TItem, TKey) 메서드

정의

조회 사전의 지정된 요소와 연결된 키를 변경합니다.Changes the key associated with the specified element in the lookup dictionary.

protected:
 void ChangeItemKey(TItem item, TKey newKey);
protected void ChangeItemKey (TItem item, TKey newKey);
member this.ChangeItemKey : 'Item * 'Key -> unit
Protected Sub ChangeItemKey (item As TItem, newKey As TKey)

매개 변수

item
TItem

키를 변경할 요소입니다.The element to change the key of.

newKey
TKey

item의 새 키입니다.The new key for item.

예외

itemnull입니다.item is null.

또는-or- keynull입니다.key is null.

item가 없는 경우item is not found.

또는-or- keyKeyedCollection<TKey,TItem>에 이미 있는 경우key already exists in the KeyedCollection<TKey,TItem>.

예제

다음 코드 예제에서는 변경 가능한 키를 지원 하도록 보호 된 ChangeItemKey 메서드를 재정의 하는 방법과 보호 된 InsertItem, RemoveItem, ClearItemsSetItem 메서드를 재정의 하 여 키와 컬렉션의 무결성을 유지 하는 방법을 보여 줍니다.The following code example shows how to override the protected ChangeItemKey method to support mutable keys, and how to override the protected InsertItem, RemoveItem, ClearItems, and SetItem methods to maintain the integrity of the keys and the collection.

코드 예제에서는 KeyedCollection<TKey,TItem>MutableKey 클래스에서 파생 되는 MutableKeys 컬렉션을 만듭니다.The code example creates the MutableKeys collection, which derives from KeyedCollection<TKey,TItem>, and the MutableKey class. MutableKey 클래스에는 설정 가능한 Key 속성이 있습니다.The MutableKey class has a settable Key property. 새 키가 속성에 할당 된 경우 속성 setter는 컬렉션의 internal (Friend Visual Basic) ChangeKey 메서드를 호출 하 여 새 키가 기존 키와 충돌 하는지 여부를 테스트 합니다.When a new key is assigned to the property, the property setter calls the internal (Friend in Visual Basic) ChangeKey method of the collection to test whether the new key would conflict with an existing key. 그렇다면 예외가 throw 되 고 속성 값을 변경 되지 않습니다.If so, an exception is thrown and the property value is not changed.

MutableKey 개체와 MutableKeys 컬렉션 간의 연결을 유지 하 고 개체가 두 개의 컬렉션에 삽입 되지 않도록 하기 위해 MutableKey 클래스에 internal (Friend Visual Basic) Collection 필드가 있습니다.In order to maintain the connection between a MutableKey object and the MutableKeys collection and to prevent an object from being inserted into two collections, the MutableKey class has an internal (Friend in Visual Basic) Collection field. 이 필드는 InsertItem 메서드와 같이 컬렉션에서 항목을 추가 및 제거 하기 위한 사용자 지정 동작을 제공 하는 보호 된 메서드에 의해 유지 관리 됩니다.This field is maintained by the protected methods that provide custom behavior for adding and removing items from the collection, such as the InsertItem method. 필드에는 항목을 컬렉션에 추가 하 고 항목이 제거 되 면 지울 때 설정 됩니다.The field is set when the item is added to a collection and cleared when the item is removed.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

// This class demonstrates one way to use the ChangeItemKey
// method to store objects with keys that can be changed. The 
// ChangeItemKey method is used to keep the internal lookup
// Dictionary in sync with the keys of the stored objects. 
//
// MutableKeys stores MutableKey objects, which have an Integer
// Key property that can be set. Therefore, MutableKeys inherits
// KeyedCollection(Of Integer, MutableKey).
//
public class MutableKeys : KeyedCollection<int, MutableKey>
{
    // This parameterless constructor delegates to the base class 
    // constructor that specifies a dictionary threshold. A
    // threshold of 0 means the internal Dictionary is created
    // the first time an object is added.
    //
    public MutableKeys() : base(null, 0) {}
    
    protected override int GetKeyForItem(MutableKey item)
    {
        // The key is MutableKey.Key.
        return item.Key;
    }

    protected override void InsertItem(int index, MutableKey newItem)
    {
        if (newItem.Collection != null) 
            throw new ArgumentException("The item already belongs to a collection.");

        base.InsertItem(index, newItem);
        newItem.Collection = this;
    }

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

        if (newItem.Collection != null) 
            throw new ArgumentException("The item already belongs to a collection.");

        base.SetItem(index, newItem);
        newItem.Collection = this;
        replaced.Collection = null;
    }

    protected override void RemoveItem(int index)
    {
        MutableKey removedItem = Items[index];

        base.RemoveItem(index);
        removedItem.Collection = null;
    }

    protected override void ClearItems()
    {
        foreach( MutableKey mk in Items )
        {
            mk.Collection = null;
        }
        
        base.ClearItems();
    }

    internal void ChangeKey(MutableKey item, int newKey)
    {
        base.ChangeItemKey(item, newKey);
    }
    
    public void Dump()
    {
        Console.WriteLine("\nDUMP:");
        if (Dictionary == null)
        {
            Console.WriteLine("    The dictionary has not been created.");
        }
        else
        {
            Console.WriteLine("    Dictionary entries");
            Console.WriteLine("    ------------------");

            foreach( KeyValuePair<int, MutableKey> kvp in Dictionary )
            {
                Console.WriteLine("    {0} : {1}", kvp.Key, kvp.Value);
            }
        }

        Console.WriteLine("\n    List of items");
        Console.WriteLine("    -------------");

        foreach( MutableKey mk in Items )
        {
            Console.WriteLine("    {0}", mk);
        }
    }
}

public class Demo
{
    public static void Main()
    {
        MutableKeys mkeys = new MutableKeys();

        // The Add method is inherited from Collection.
        //
        mkeys.Add(new MutableKey(110072674, "Widget"));
        mkeys.Add(new MutableKey(110072675, "Sprocket"));

        mkeys.Dump();
    
        Console.WriteLine("\nCreate and insert a new item:");
        MutableKey test = new MutableKey(110072684, "Gear");
        mkeys.Insert(1, test);

        mkeys.Dump();

        try
        {
            Console.WriteLine("\nTry to insert the item again:");
            mkeys.Insert(1, test);
        }
        catch(ArgumentException ex)
        {
            Console.WriteLine("Error: {0}", ex.Message);
        }

        Console.WriteLine("\nChange the Key property of the item:");
        test.Key = 100000072;

        mkeys.Dump();

        try
        {
            Console.WriteLine("\nTry to set the Key property to an existing key:");
            test.Key = 110072674;
        }
        catch(ArgumentException ex)
        {
            Console.WriteLine("Error: {0}", ex.Message);
        }

        mkeys.Dump();
    }
    
    private static void Display(MutableKeys order)
    {
        Console.WriteLine();
        foreach( MutableKey item in order )
        {
            Console.WriteLine(item);
        }
    }
}

// This class has a key that can be changed.
// 
public class MutableKey
{

    public MutableKey(int newKey, string newValue)
    {
        _key = newKey;
        Value = newValue;
    } //New
    
    public string Value;
    internal MutableKeys Collection;
    
    private int _key;
    public int Key    
    {
        get
        {
            return _key;
        }
        set
        {
            if (Collection != null)
            {
                Collection.ChangeKey(this, value);
            }

            _key = value;
        }
    }

    public override string ToString()
    {
        return String.Format("{0,9} {1}", _key, Value);
    }
}

/* This code example produces the following output:

DUMP:
    Dictionary entries
    ------------------
    110072674 : 110072674 Widget
    110072675 : 110072675 Sprocket

    List of items
    -------------
    110072674 Widget
    110072675 Sprocket

Create and insert a new item:

DUMP:
    Dictionary entries
    ------------------
    110072674 : 110072674 Widget
    110072675 : 110072675 Sprocket
    110072684 : 110072684 Gear

    List of items
    -------------
    110072674 Widget
    110072684 Gear
    110072675 Sprocket

Try to insert the item again:
Error: The item already belongs to a collection.

Change the Key property of the item:

DUMP:
    Dictionary entries
    ------------------
    110072674 : 110072674 Widget
    110072675 : 110072675 Sprocket
    100000072 : 100000072 Gear

    List of items
    -------------
    110072674 Widget
    100000072 Gear
    110072675 Sprocket

Try to set the Key property to an existing key:
Error: An item with the same key has already been added.

DUMP:
    Dictionary entries
    ------------------
    110072674 : 110072674 Widget
    110072675 : 110072675 Sprocket
    100000072 : 100000072 Gear

    List of items
    -------------
    110072674 Widget
    100000072 Gear
    110072675 Sprocket
 */
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

' This class demonstrates one way to use the ChangeItemKey
' method to store objects with keys that can be changed. The 
' ChangeItemKey method is used to keep the internal lookup
' Dictionary in sync with the keys of the stored objects. 
'
' MutableKeys stores MutableKey objects, which have an Integer
' Key property that can be set. Therefore, MutableKeys inherits
' KeyedCollection(Of Integer, MutableKey).
'
Public Class MutableKeys
    Inherits KeyedCollection(Of Integer, MutableKey)

    ' This parameterless constructor delegates to the base class 
    ' constructor that specifies a dictionary threshold. A
    ' threshold of 0 means the internal Dictionary is created
    ' the first time an object is added.
    '
    Public Sub New()
        MyBase.New(Nothing, 0)
    End Sub
    
    Protected Overrides Function GetKeyForItem( _
        ByVal item As MutableKey) As Integer

        ' The key is MutableKey.Key.
        Return item.Key   
    End Function

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

        If newItem.Collection IsNot Nothing Then _
            Throw New ArgumentException("The item already belongs to a collection.")

        MyBase.InsertItem(index, newItem)
        newItem.Collection = Me
    End Sub

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

        Dim replaced As MutableKey = Items(index)

        If newItem.Collection IsNot Nothing Then _
            Throw New ArgumentException("The item already belongs to a collection.")

        MyBase.SetItem(index, newItem)
        newItem.Collection = Me
        replaced.Collection = Nothing
    End Sub

    Protected Overrides Sub RemoveItem(ByVal index As Integer)
        Dim removedItem As MutableKey = Items(index)

        MyBase.RemoveItem(index)
        removedItem.Collection = Nothing
    End Sub

    Protected Overrides Sub ClearItems()
        For Each mk As MutableKey In Items
            mk.Collection = Nothing
        Next
        
        MyBase.ClearItems()
    End Sub

    Friend Sub ChangeKey(ByVal item As MutableKey, _
        ByVal newKey As Integer)

        MyBase.ChangeItemKey(item, newKey)
    End Sub
    
    Public Sub Dump()
        Console.WriteLine(vbLf & "DUMP:")
        If Dictionary Is Nothing Then
            Console.WriteLine("    The dictionary has not been created.")
        Else
            Console.WriteLine("    Dictionary entries")
            Console.WriteLine("    ------------------")

            For Each kvp As KeyValuePair(Of Integer, MutableKey) In Dictionary
                Console.WriteLine("    {0} : {1}", kvp.Key, kvp.Value)
            Next
        End If

        Console.WriteLine(vbLf & "    List of items")
        Console.WriteLine("    -------------")

        For Each mk As MutableKey In Items
            Console.WriteLine("    {0}", mk)
        Next
    End Sub

End Class

Public Class Demo
    
    Public Shared Sub Main() 

        Dim mkeys As New MutableKeys()

        ' The Add method is inherited from Collection.
        '
        mkeys.Add(New MutableKey(110072674, "Widget"))
        mkeys.Add(New MutableKey(110072675, "Sprocket"))

        mkeys.Dump() 
    
        Console.WriteLine(vbLf & "Create and insert a new item:")
        Dim test As New MutableKey(110072684, "Gear")
        mkeys.Insert(1, test)

        mkeys.Dump()

        Try
            Console.WriteLine(vbLf & "Try to insert the item again:")
            mkeys.Insert(1, test)
        Catch ex As ArgumentException
            Console.WriteLine("Error: {0}", ex.Message)
        End Try

        Console.WriteLine(vbLf & "Change the Key property of the item:")
        test.Key = 100000072

        mkeys.Dump()

        Try
            Console.WriteLine(vbLf & "Try to set the Key property to an existing key:")
            test.Key = 110072674
        Catch ex As ArgumentException
            Console.WriteLine("Error: {0}", ex.Message)
        End Try

        mkeys.Dump()

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

' This class has a key that can be changed.
' 
Public Class MutableKey

    Public Sub New(ByVal newKey As Integer, ByVal newValue As String)
        _key = newKey
        Value = newValue
    End Sub
    
    Public Value As String
    Friend Collection As MutableKeys
    
    Private _key As Integer
    Public Property Key As Integer 
        Get
            Return _key
        End Get
        Set
            If Collection IsNot Nothing Then
                Collection.ChangeKey(Me, value)
            End If

            _key = value
        End Set
    End Property

    Public Overrides Function ToString() As String 
        Return String.Format("{0,9} {1}", _key, Value)
    End Function
        
End Class

' This code example produces the following output:
'
'DUMP:
'    Dictionary entries
'    ------------------
'    110072674 : 110072674 Widget
'    110072675 : 110072675 Sprocket
'
'    List of items
'    -------------
'    110072674 Widget
'    110072675 Sprocket
'
'Create and insert a new item:
'
'DUMP:
'    Dictionary entries
'    ------------------
'    110072674 : 110072674 Widget
'    110072675 : 110072675 Sprocket
'    110072684 : 110072684 Gear
'
'    List of items
'    -------------
'    110072674 Widget
'    110072684 Gear
'    110072675 Sprocket
'
'Try to insert the item again:
'Error: The item already belongs to a collection.
'
'Change the Key property of the item:
'
'DUMP:
'    Dictionary entries
'    ------------------
'    110072674 : 110072674 Widget
'    110072675 : 110072675 Sprocket
'    100000072 : 100000072 Gear
'
'    List of items
'    -------------
'    110072674 Widget
'    100000072 Gear
'    110072675 Sprocket
'
'Try to set the Key property to an existing key:
'Error: An item with the same key has already been added.
'
'DUMP:
'    Dictionary entries
'    ------------------
'    110072674 : 110072674 Widget
'    110072675 : 110072675 Sprocket
'    100000072 : 100000072 Gear
'
'    List of items
'    -------------
'    110072674 Widget
'    100000072 Gear
'    110072675 Sprocket

설명

이 메서드는 item에 포함 된 키를 수정 하지 않습니다. 단지 조회 사전에 저장 된 키를 대체 합니다.This method does not modify the key embedded in item; it simply replaces the key saved in the lookup dictionary. 따라서 newKey item에 포함 된 키와 다른 경우 GetKeyForItem에서 반환 된 키를 사용 하 여 item에 액세스할 수 없습니다.Therefore, if newKey is different from the key that is embedded in item, you cannot access item by using the key returned by GetKeyForItem.

KeyedCollection<TKey,TItem>에 조회 사전이 없는 경우이 메서드는 아무 작업도 수행 하지 않습니다.This method does nothing if the KeyedCollection<TKey,TItem> does not have a lookup dictionary.

KeyedCollection<TKey,TItem>의 모든 키는 고유 해야 합니다.Every key in a KeyedCollection<TKey,TItem> must be unique. 키를 null수 없습니다.A key cannot be null.

이 방법은 O(1) 작업에 설명 합니다.This method is an O(1) operation.

구현자 참고 사항Notes for Implementers

항목에 포함 된 키를 수정 하려면 먼저 조회 사전의 키를 업데이트 하려면이 메서드를 호출 해야 합니다.Before modifying the key embedded in an item, you must call this method to update the key in the lookup dictionary. 사전 생성 임계값이-1 인 경우에는이 메서드를 호출할 필요가 없습니다.If the dictionary creation threshold is -1, calling this method is not necessary.

ChangeItemKey 메서드를 파생 클래스의 공용 메서드로 노출 하지 마십시오.Do not expose the ChangeItemKey method as a public method of a derived class. 이 메서드를 잘못 사용 하면 조회 사전이 동기화 항목 키입니다.Misuse of this method puts the lookup dictionary out of sync with item keys. 예를 들어 null 키를 설정 하 고 다른 값으로 설정 하면 항목에 대 한 여러 키가 조회 사전에 추가 됩니다.For example, setting the key to null and then setting it to another value adds multiple keys for an item to the lookup dictionary. 변경할 수 있는 항목 키를 허용 하는 내부적으로이 메서드를 노출 합니다: 항목에 대 한 키가 변경 조회 사전의 키를 변경 하려면이 메서드를 사용 합니다.Expose this method internally to allow mutable item keys: When the key for an item changes, this method is used to change the key in the lookup dictionary.

적용 대상

추가 정보