2013-12-14 2 views
3

하나의 배열을 읽기 전용으로 만들 수 있습니다. 배열에 대한 설정 값은 허용되지 않습니다.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 만 있어야합니다.

+1

http://msdn.microsoft.com/en-us/library/53kysx7b(v=vs.110).aspx –

답변

4

Array.AsReadOnly<T>(T[] array) 메서드를 정의해야합니다.이 메서드는 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 문서를 찾을 수 있습니다. 적어도 동급 외부에서 -


은 또는 당신은 단순히 읽기 전용 배열을하기 위해

public T getElement(int index) { return array[index]; } 

와 같은 게터-방법을 정의 할 수 있습니다? Array.IsReadOnly MSDN 설명서의 사용에 관한


이 속성은 항상 모든 배열에 대한 거짓이라고 말한다.

즉, arr.IsReadOnly 대신 IList<T>.IsReadOnly을 사용해야합니다.

here

+0

안녕하세요, 감사합니다. 샘플을 정교하게 만드시겠습니까? 나는 이것이 허용되기를 원하지 않는다. (int i = 0; i

+0

업데이트했습니다. –

+0

정확히 달성하기를 원하십니까? –

6

배열은 본질적으로 변경 가능하며 래퍼를 사용해야하는 동작을 얻으려면 ReadOnlyCollection<T>. 배열의 읽기 전용 사본을 만들려면 arr.AsReadOnly()

+0

안녕을 참조하십시오. 이 배열 (여기서 arr)은 읽기 전용이어야합니다. 그것은 가능한가? arr.AsReadOnly()는 ReadOnlyCollection 을 반환합니다. 괜찮아요.하지만 그건 내 배열이 아니에요. 그것은 또 다른 대상입니다. –

+2

+1. @ kumarch1 - "배열은 본질적으로 변경 가능"이외에 필요한 다른 정보는 무엇입니까? .Net에는 "읽기 전용 배열"과 같은 것은 없습니다. –

관련 문제