C# 数组 - AsReadOnly() 方法

C# 数组 AsReadOnly() 方法用于返回指定数组的只读包装器。此方法可防止通过包装器修改数组元素,同时仍允许我们查看这些元素。

语法

以下是 C# 数组 AsReadOnly() 方法的语法 -

public static System.Collections.ObjectModel.
Array.AsReadOnly<T> (T[] array);

参数

此函数接受一个一维数组(T[] 数组)作为参数,并将其包装在只读 (ReadOnlyCollection<T>) 包装器中。

返回值

此函数返回指定数组的只读包装器。

示例 1

让我们创建一个 AsReadOnly() 方法的基本示例来显示只读集合 -

using System;
using System.Collections.ObjectModel;

class Program {
   static void Main() {
      // 原始数组
      int[] numbers = { 1, 2, 3, 4, 5 };
   
      // 将数组包装为只读集合
      ReadOnlyCollection<int> readOnlyNumbers = Array.AsReadOnly(numbers);
   
      // 显示只读集合
      Console.WriteLine("Read-only collection elements:");
      foreach (int num in readOnlyNumbers) {
         Console.WriteLine(num);
      }
	  
      // 原始数组仍然可以修改
      numbers[0] = 10;
   
      Console.WriteLine("After modifying the original array:");
      foreach (int num in readOnlyNumbers) {
         Console.WriteLine(num);
      }
   }
}

输出

以下是输出 -

Read-only collection elements:
1
2
3
4
5

After modifying the original array:
10
2
3
4
5

示例 2:自定义对象的只读集合

以下示例使用 AsReadOnly() 方法将自定义对象转换为只读集合 -

using System;
using System.Collections.ObjectModel;

class Person {
   public string Name { get; set; }
   public int Age { get; set; }

   public override string ToString() {
      return $"Name: {Name}, Age: {Age}";
   }
}

class Program {
   static void Main() {
      // 自定义对象数组 (Person)
      Person[] people = new Person[] {
         new Person { Name = "Aman", Age = 25 },
         new Person { Name = "Akash", Age = 30 },
         new Person { Name = "Vikash", Age = 35 }
      };

      // 将数组包装为只读集合
      ReadOnlyCollection<Person> readOnlyPeople = Array.AsReadOnly(people);

      Console.WriteLine("Read-only collection of people:");
      foreach (var person in readOnlyPeople) {
         Console.WriteLine(person);
      }
   }
}

输出

以下是输出 -

Read-only collection of people:
Name: Aman, Age: 25
Name: Akash, Age: 30
Name: Vikash, Age: 35

示例 3:如果您修改了只读集合

这是 AsReadOnly() 方法的另一个示例。如果您要修改只读集合,则会引发编译时错误 -

using System;
using System.Collections.ObjectModel;

class Person {
   public string Name { get; set; }
   public int Age { get; set; }

   public override string ToString() {
      return $"Name: {Name}, Age: {Age}";
   }
}
class Program {
   static void Main() {
      // 自定义对象数组(Person)
      Person[] people = new Person[] {
          new Person { Name = "Aman", Age = 25 },
          new Person { Name = "Akash", Age = 30 },
          new Person { Name = "Vikash", Age = 35 }
      };

      // 将数组包装为只读集合
      ReadOnlyCollection<Person> readOnlyPeople = Array.AsReadOnly(people);
      
      // 尝试修改只读集合会引发异常
      readOnlyPeople[0] = new Person { Name = "David", Age = 40 };
   }
}

输出

以下是输出 -

ERROR!
Main.cs(31,9): error CS0200: Property or indexer 'ReadOnlyCollection<Person>.this[int]' cannot be assigned to -- it is read only

csharp_array_class.html