KeyedCollection.ChangeItemKey メソッドとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > KeyedCollection.ChangeItemKey メソッドの意味・解説 

KeyedCollection.ChangeItemKey メソッド

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

検索ディクショナリの指定した要素関連付けられたキー変更します

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

Protected Sub ChangeItemKey ( _
    item As TItem, _
    newKey As TKey _
)
Dim item As TItem
Dim newKey As TKey

Me.ChangeItemKey(item, newKey)
protected void ChangeItemKey (
    TItem item,
    TKey newKey
)
protected:
void ChangeItemKey (
    TItem item, 
    TKey newKey
)
protected void ChangeItemKey (
    TItem item, 
    TKey newKey
)
protected function ChangeItemKey (
    item : TItem, 
    newKey : TKey
)

パラメータ

item

変更するキー要素

newKey

item新しキー

例外例外
例外種類条件

ArgumentNullException

itemnull 参照 (Visual Basic では Nothing) です。

または

keynull 参照 (Visual Basic では Nothing) です。

ArgumentException

item が見つかりません。

または

key は KeyedCollection に既に存在します

解説解説

このメソッドitem埋め込まれキー変更せず、単に検索ディクショナリに保存されキー置き換えます。したがってnewKeyitem埋め込まれキー異な場合は、GetKeyForItem で返されるキー使用して itemアクセスすることはできません。

KeyedCollection検索ディクショナリを持たない場合、このメソッドは何も実行しません。

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

このメソッドは O(1) 操作です。

実装についてのメモ

項目に埋め込まれキー変更した後、このメソッド呼び出して検索ディクショナリのキー更新する必要があります。ディクショナリ作成しきい値が –1 の場合は、このメソッド呼び出す必要はありません。

ChangeItemKey メソッドを、派生クラスパブリック メソッドとして公開しないください。このメソッド不正に使用すると、検索ディクショナリが項目キー同期されなくなります。たとえば、キーnull 参照 (Visual Basic では Nothing) に設定してから、そのキー別の値に設定すると、特定の項目に対して複数キー検索ディクショナリに追加されます。このメソッド内部的に公開して項目キー変更可能にます。特定の項目のキー変更になる場合は、このメソッド使用して検索ディクショナリのキー変更します

使用例使用例

このコード例では、ChangeItemKey プロテクト メソッドオーバーライドして変更可能なキーサポートする方法、および InsertItem、RemoveItem、ClearItems、および SetItem の各プロテクト メソッドオーバーライドしてキーコレクション整合性維持する方法示します

KeyedCollection クラスおよび MutableKey クラスから派生した MutableKeys コレクション作成しますMutableKey クラスには、設定可能な Key プロパティ含まれています。新しキープロパティ割り当てると、プロパティ Set アクセス操作子はコレクションinternal (Visual Basic の場合Friend) ChangeKey メソッド呼び出して新しキー既存キー競合するかどうかテストします競合する場合例外スローされ、プロパティ値は変更されません。

MutableKey オブジェクトMutableKeys コレクション接続維持するために、また、オブジェクト2 つコレクションの間に挿入されないようにするために、MutableKey クラスには internal (Visual Basic の場合Friend) Collection フィールドあります。このフィールドは、InsertItem メソッドなど、コレクションの項目の追加および削除のためのカスタム動作提供するプロテクト メソッドによって維持されます。このフィールドは、項目がコレクション追加されるときに設定され、項目が削除されるときにクリアされます

Imports System
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 'New
    
    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
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
 */
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
KeyedCollection ジェネリック クラス
KeyedCollection メンバ
System.Collections.ObjectModel 名前空間
GetKeyForItem
Item



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

辞書ショートカット

すべての辞書の索引

「KeyedCollection.ChangeItemKey メソッド」の関連用語

KeyedCollection.ChangeItemKey メソッドのお隣キーワード
検索ランキング

   

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



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

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

©2024 GRAS Group, Inc.RSS