📜  C#|获取OrderedDictionary的只读副本

📅  最后修改于: 2021-05-29 19:51:11             🧑  作者: Mango

OrderedDictionary.AsReadOnly方法返回当前OrderedDictionary集合的只读副本。

句法:

public System.Collections.Specialized.OrderedDictionary AsReadOnly ();

返回值:当前OrderedDictionary集合的只读副本。

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to get a read-only
// copy of the OrderedDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver method
    public static void Main()
    {
  
        // Creating a orderedDictionary named myDict
        OrderedDictionary myDict = new OrderedDictionary();
  
        // Adding key and value in myDict
        myDict.Add("key1", "value1");
        myDict.Add("key2", "value2");
        myDict.Add("key3", "value3");
        myDict.Add("key4", "value4");
        myDict.Add("key5", "value5");
  
        // To Get a read-only copy of
        // the OrderedDictionary
        OrderedDictionary myDict_1 = myDict.AsReadOnly();
  
        // Checking if myDict_1 is read-only
        Console.WriteLine(myDict_1.IsReadOnly);
    }
}

输出:

True

范例2:

// C# code to get a read-only
// copy of the OrderedDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver method
    public static void Main()
    {
  
        // Creating a orderedDictionary named myDict
        OrderedDictionary myDict = new OrderedDictionary();
  
        // Adding key and value in myDict
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
  
        // To Get a read-only copy of
        // the OrderedDictionary
        OrderedDictionary myDict_1 = myDict.AsReadOnly();
  
        // Checking if myDict_1 is read-only
        Console.WriteLine(myDict_1.IsReadOnly);
    }
}

输出:

True

注意: AsReadOnly方法围绕当前OrderedDictionary集合创建一个只读包装器。对OrderedDictionary集合所做的更改将反映在只读副本中。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.ordereddictionary.asreadonly?view=netframework-4.7.2