是否可以在c#中将数组声明为只读?

是否可以在c#中将数组声明为只读?,c#,arrays,readonly,C#,Arrays,Readonly,是否可以将一个数组设为只读。这样就不允许将值设置为数组 这里是我用readonly关键字声明数组的方法。然后使用IsReadOnly属性检查该数组是否为只读。但它永远不会变成真的 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrivateExposeConsoleApp { class Program { priva

是否可以将一个数组设为只读。这样就不允许将值设置为数组

这里是我用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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间PrivateExposeConsoleApp
{
班级计划
{
私有静态只读int[]arr=newint[3]{1,2,3};
静态void Main(字符串[]参数)
{
//围绕阵列创建只读IList包装。
IList myList=Array.AsReadOnly(arr);
尝试
{
//尝试通过包装器更改数组的值。
arr[2]=100;
Console.WriteLine(“数组元素”);
foreach(内部i在arr中)
{
WriteLine(“{0}-{1}”,i+“->”,i);
}
Console.WriteLine(“--------------”);
Console.WriteLine(“列表元素”);
foreach(myList中的int j)
{
WriteLine(“{0}-{1}”,j+“->”,j);
}
//尝试通过包装器更改列表的值。
myList[3]=50;
}
捕获(不支持例外e)
{
WriteLine(“{0}-{1}”,e.GetType(),e.Message);
Console.WriteLine();
}
//如果(arr.IsReadOnly)
//{
//WriteLine(“数组是只读的”);
//}
//否则
//{
//对于(int i=0;i

这里看到我的评论部分。如果我取消对此的注释,我的arr将永远不会变为只读。在声明中,我明确地将arr定义为只读,数据为{1,2,3}。我不希望重新设置此值。它应该始终仅为1,2,3。

数组本身是可变的,要获得所需的行为,需要使用包装器,
ReadOnlyCollection
。您可以使用
arr.AsReadOnly()

方法创建数组的只读副本。在数组类本身上定义的方法
array.AsReadOnly(T[]array)
应该用于此目的

该方法将数组作为参数(要使其成为只读的数组),并返回一个
ReadOnlyCollection

例如:

// 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.
为了使您的数组成为只读的(至少是从它的类之外)


关于Array.isRead的使用,只有MSDN文档说明

对于所有数组,此属性始终为false

这意味着您必须使用
IList.IsReadOnly
而不是arr.IsReadOnly


请参见

Hi。我只希望这个数组(这里是arr)是只读的。可能吗?arr.AsReadOnly()将返回ReadOnlyCollection。那很好,但那不是我的阵列。那是另一个物体@kumarch1-除了“数组本身是可变的”之外,您还需要哪些其他信息?Net中没有“只读数组”这样的东西。嗨,谢谢。你能不能用一个样品来详细说明一下?我只是不希望允许这样做(inti=0;ipublic T getElement(int index) { return array[index]; }