是否可以只读一个数组。这样就不允许将值设置为数组。
这里我尝试使用readonly关键字来声明数组。然后我通过使用IsReadOnly属性检查该数组是否只读。但它永远不会回归真实。
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。
答案 0 :(得分:6)
数组本质上是可变的,为了获得你想要的行为,你需要使用包装器ReadOnlyCollection<T>
。您可以使用arr.AsReadOnly()
答案 1 :(得分:4)
在Array类本身上定义的方法Array.AsReadOnly<T>(T[] array)
应该用于此目的。
该方法将数组作为参数(您想要使其成为只读参数)并返回ReadOnlyCollection<T>
。
一个例子如下:
// declaration of a normal example array
string[] myArray = new string[] { "StackOverflow", "SuperUser", "MetaStackOverflow" };
// declaration of a new ReadOnlyCollection whose elements are of type string
// the string array is passed through the constructor
// that's is where our array is passed into its new casing
// as a matter of fact, the ReadOnlyCollection is a wrapper for ordinary collection classes such as arrays
ReadOnlyCollection<string> myReadOnlyCollection = new ReadOnlyCollection<string>(maArray);
Console.WriteLine(myReadOnlyCollection[0]); // would work fine since the collection is read-only
Console.WriteLine(myReadOnlyCollection[1]); // would work fine since the collection is read-only
Console.WriteLine(myReadOnlyCollection[2]); // would work fine since the collection is read-only
myReadOnlyCollection[0] = "ServerFault"; // the [] accessor is neither defined nor would it be allowed since the collection is read-only.
Here您可以找到相应的MSDN文档。
或者,您可以简单地定义一个getter方法,例如
public T getElement(int index) { return array[index]; }
为了使你的数组只读 - 至少从它的类之外?
关于您使用Array.IsReadOnly,MSDN文档说明了
对于所有数组,此属性始终为false。
这意味着你必须使用IList<T>.IsReadOnly
而不是arr.IsReadOnly。
请参阅here