하나의 배열을 읽기 전용으로 만들 수 있습니다. 배열에 대한 설정 값은 허용되지 않습니다.C#에서 읽기 전용으로 배열을 선언 할 수 있습니까?
여기에 배열을 선언하기위한 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은 결코 읽기 전용이되지 않습니다. 선언에서 명시 적으로 arr을 {1,2,3}과 같은 데이터로 읽기 전용으로 정의했습니다. 나는이 가치가 rewitten 싶지 않아요. 항상 1,2,3 만 있어야합니다.
http://msdn.microsoft.com/en-us/library/53kysx7b(v=vs.110).aspx –