是否可以将一个数组设置为只读,以使对该数组的赋值不被允许。
我尝试使用readonly关键字来声明数组,然后通过使用IsReadOnly属性来检查该数组是否为只读。但它从来没有返回过true。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PrivateExposeConsoleApp
{
class Program
{
private static readonly int[] arr = new int[3] { 1,2,3 };
static void Main(string[] args)
{
// Create a read-only IList wrapper around the array.
IList<int> myList = Array.AsReadOnly(arr);
try
{
// Attempt to change a value of array through the wrapper.
arr[2] = 100;
Console.WriteLine("Array Elements");
foreach (int i in arr)
{
Console.WriteLine("{0} - {1}", i + "->", i);
}
Console.WriteLine("---------------");
Console.WriteLine("List Elements");
foreach (int j in myList)
{
Console.WriteLine("{0} - {1}", j + "->", j);
}
// Attempt to change a value of list through the wrapper.
myList[3] = 50;
}
catch (NotSupportedException e)
{
Console.WriteLine("{0} - {1}", e.GetType(), e.Message);
Console.WriteLine();
}
//if (arr.IsReadOnly)
//{
// Console.WriteLine("array is readonly");
//}
//else
//{
// for (int i = 0; i < arr.Length; i++)
// {
// arr[i] = i + 1;
// }
// foreach (int i in arr)
// {
// Console.WriteLine(i);
// }
//}
Console.ReadKey();
}
}
}
下面是我的注释部分。如果我取消注释,我的数组将永远不会变得只读。在声明时,我明确将arr定义为只读,数据为{1,2,3}。我不希望这个值被重写。它应该始终是1、2、3。