当前位置: 首页>>代码示例>>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;未经允许,请勿转载。