此方法用于返回指定数组的只读包装器。
用法:
public static System.Collections.ObjectModel. ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
在此,T是数组元素的类型。
返回值:此方法返回一个只读ReadOnlyCollection <T>包装器。
异常:如果数组为null,则此方法引发ArgumentNullException。
下面是说明Array.AsReadOnly(T [])方法的示例:
范例1:
// C# program to demonstrate
// AsReadOnly() method
using System;
using System.Collections.Generic;
public class GFG {
// Main Method
public static void Main()
{
// Creating and initializing new the String
String[] myArr = {"Sun", "Mon", "Tue", "Thu"};
// Display the values of the myArr.
Console.WriteLine("Initial Array:");
// calling the PrintIndexAndValues()
// method to print
PrintIndexAndValues(myArr);
// Create a read-only IList
// wrapper around the array.
IList<String> myList = Array.AsReadOnly(myArr);
// Display the values of the read-only myList.
Console.WriteLine("Read-only Array:");
// calling the PrintIndexAndValues()
// method to print
PrintIndexAndValues(myList);
}
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
Console.WriteLine();
}
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(IList<String> myList)
{
for (int i = 0; i < myList.Count; i++) {
Console.WriteLine("{0}", myList[i]);
}
}
}
输出:
Initial Array: Sun Mon Tue Thu Read-only Array: Sun Mon Tue Thu
范例2:
// C# program to demonstrate
// AsReadOnly() method
// For ArgumentNullException
using System;
using System.Collections.Generic;
public class GFG {
// Main Method
public static void Main()
{
try {
// Creating and initializing new
// the String with a null value
String[] myArr = null;
// Create a read-only IList
// wrapper around the array.
IList<String> myList = Array.AsReadOnly(myArr);
// Display the values of
// the read-only myList.
Console.WriteLine("Read-only Array:");
// calling the PrintIndexAndValues()
// method to print
PrintIndexAndValues(myList);
}
catch (ArgumentNullException e) {
Console.Write("Exception Thrown:");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining the method PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
Console.WriteLine();
}
// Defining the method PrintIndexAndValues
public static void PrintIndexAndValues(IList<String> myList)
{
for (int i = 0; i < myList.Count; i++) {
Console.WriteLine("{0}", myList[i]);
}
}
}
输出:
Exception Thrown:System.ArgumentNullException
参考:
相关用法
- C# Dictionary.Add()用法及代码示例
- C# Math.Max()用法及代码示例
- C# Math.Min()用法及代码示例
- C# Decimal.Add()用法及代码示例
- C# Math.Tan()用法及代码示例
- C# Math.Cos()用法及代码示例
- C# Math.Sin()用法及代码示例
- C# SortedDictionary.Add()用法及代码示例
- C# Math.Abs()方法用法及代码示例
- C# String.Contains()用法及代码示例
- C# Math.Exp()用法及代码示例
注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 C# | Array.AsReadOnly(T[]) Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。