当前位置: 首页>>代码示例>>C#>>正文


C# Array.AsReadOnly<T>方法代码示例

本文整理汇总了C#中System.Array.AsReadOnly<T>方法的典型用法代码示例。如果您正苦于以下问题:C# Array.AsReadOnly<T>方法的具体用法?C# Array.AsReadOnly<T>怎么用?C# Array.AsReadOnly<T>使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Array的用法示例。


在下文中一共展示了Array.AsReadOnly<T>方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

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

public class SamplesArray  {
 
   public static void Main()  {
 
      // Create and initialize a new string array.
      String[] myArr = { "The", "quick", "brown", "fox" };
 
      // Display the values of the array.
      Console.WriteLine( "The string array initially contains the following values:" );
      PrintIndexAndValues( myArr );

      // Create a read-only IList wrapper around the array.
      IList<String> myList = Array.AsReadOnly( myArr );
      
      // Display the values of the read-only IList.
      Console.WriteLine( "The read-only IList contains the following values:" );
      PrintIndexAndValues( myList );

      // Attempt to change a value through the wrapper.
      try  {
         myList[3] = "CAT";
      }
      catch ( NotSupportedException e )  {
         Console.WriteLine( "{0} - {1}", e.GetType(), e.Message );
         Console.WriteLine();
      }

      // Change a value in the original array.
      myArr[2] = "RED";

      // Display the values of the array.
      Console.WriteLine( "After changing the third element, the string array contains the following values:" );
      PrintIndexAndValues( myArr );

      // Display the values of the read-only IList.
      Console.WriteLine( "After changing the third element, the read-only IList contains the following values:" );
      PrintIndexAndValues( myList );
   }
 
   public static void PrintIndexAndValues( String[] myArr )  {
      for ( int i = 0; i < myArr.Length; i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, myArr[i] );
      }
      Console.WriteLine();
   }

   public static void PrintIndexAndValues( IList<String> myList )  {
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, myList[i] );
      }
      Console.WriteLine();
   }
}
开发者ID:.NET开发者,项目名称:System,代码行数:57,代码来源:Array.AsReadOnly

输出:

The string array initially contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

The read-only IList contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

System.NotSupportedException - Collection is read-only.

After changing the third element, the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : RED
   [3] : fox

After changing the third element, the read-only IList contains the following values:
   [0] : The
   [1] : quick
   [2] : RED
   [3] : fox


注:本文中的System.Array.AsReadOnly<T>方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。