是否可以只读一个数组。这样数组的设置值将不被允许。是否有可能在c#中声明一个数组为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永远不会变为只读。在声明中,我清楚地将arr定义为只读数据{1,2,3}。我不希望这个价值被重新发现。它应该始终只有1,2,3。
http://msdn.microsoft.com/en-us/library/53kysx7b(v=vs.110).aspx –