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

Cha*_*mar 4 c# arrays readonly

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

这里我尝试使用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这里看我评论的部分.如果我取消注释,我的arr永远不会变成只读.在声明中,我明确地将数据定义为只读,数据为{1,2,3}.我不希望这个值重新开始.它应该总是1,2,3.

Wil*_*ull 6

数组本质上是可变的,并且为了获得你想要的行为,你需要使用包装器ReadOnlyCollection<T>.您可以使用创建阵列的只读副本 arr.AsReadOnly()

  • +1.@ kumarch1 - 除了"数组本质上是可变的"之外,还需要哪些其他信息?在.Net中没有像"只读数组"这样的东西. (2认同)

mar*_*man 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.
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到相应的 MSDN 文档。


或者,您可以简单地定义一个 getter 方法,例如

public T getElement(int index) { return array[index]; }
Run Code Online (Sandbox Code Playgroud)

为了使你的数组​​只读 - 至少从它的类之外?


关于您对 Array.IsReadOnly 的使用,MSDN 文档说

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

这意味着您必须使用IList<T>.IsReadOnlyarr.IsReadOnly 来代替。

这里