當前位置: 首頁>>代碼示例>>C#>>正文


C# ReadOnlyCollection<T>類代碼示例

本文整理匯總了C#中System.Collections.ObjectModel.ReadOnlyCollection<T>的典型用法代碼示例。如果您正苦於以下問題:C# ReadOnlyCollection<T>類的具體用法?C# ReadOnlyCollection<T>怎麽用?C# ReadOnlyCollection<T>使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ReadOnlyCollection<T>類屬於System.Collections.ObjectModel命名空間,在下文中一共展示了ReadOnlyCollection<T>類的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();

        dinosaurs.Add("Tyrannosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Compsognathus");

        ReadOnlyCollection<string> readOnlyDinosaurs = 
            new ReadOnlyCollection<string>(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in readOnlyDinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nCount: {0}", readOnlyDinosaurs.Count);

        Console.WriteLine("\nContains(\"Deinonychus\"): {0}", 
            readOnlyDinosaurs.Contains("Deinonychus"));

        Console.WriteLine("\nreadOnlyDinosaurs[3]: {0}", 
            readOnlyDinosaurs[3]);

        Console.WriteLine("\nIndexOf(\"Compsognathus\"): {0}", 
            readOnlyDinosaurs.IndexOf("Compsognathus"));

        Console.WriteLine("\nInsert into the wrapped List:");
        Console.WriteLine("Insert(2, \"Oviraptor\")");
        dinosaurs.Insert(2, "Oviraptor");

        Console.WriteLine();
        foreach( string dinosaur in readOnlyDinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        string[] dinoArray = new string[readOnlyDinosaurs.Count + 2];
        readOnlyDinosaurs.CopyTo(dinoArray, 1);

        Console.WriteLine("\nCopied array has {0} elements:", 
            dinoArray.Length);
        foreach( string dinosaur in dinoArray )
        {
            Console.WriteLine("\"{0}\"", dinosaur);
        }
    }
}
開發者ID:.NET開發者,項目名稱:System.Collections.ObjectModel,代碼行數:57,代碼來源:ReadOnlyCollection

輸出:

Tyrannosaurus
Amargasaurus
Deinonychus
Compsognathus

Count: 4

Contains("Deinonychus"): True

readOnlyDinosaurs[3]: Compsognathus

IndexOf("Compsognathus"): 3

Insert into the wrapped List:
Insert(2, "Oviraptor")

Tyrannosaurus
Amargasaurus
Oviraptor
Deinonychus
Compsognathus

Copied array has 7 elements:
""
"Tyrannosaurus"
"Amargasaurus"
"Oviraptor"
"Deinonychus"
"Compsognathus"
""


注:本文中的System.Collections.ObjectModel.ReadOnlyCollection<T>類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。