C# में Array.AsReadOnly(T[]) विधि निर्दिष्ट सरणी के लिए केवल-पढ़ने के लिए रैपर देता है, जो केवल-पढ़ने के लिए ReadOnlyCollection
सिंटैक्स
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
यहां, टी सरणी के तत्वों का प्रकार है, जबकि सरणी टी [] एक-आयामी शून्य-आधारित सरणी है।
आइए अब Array.AsReadOnly(T[]) पद्धति को लागू करने के लिए एक उदाहरण देखें -
उदाहरण
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
String[] arr = { "John", "Tom", "Katie", "Brad" };
// read-only IList wrapper
IList<String> list = Array.AsReadOnly( arr );
// Display the values of the read-only IList.
Console.WriteLine( "Initial read-only IList..." );
display( list );
// Let us now change the read-only wrapper
try {
list[0] = "Kevin";
list[1] = "Bradley";
}
catch ( NotSupportedException e ) {
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message );
Console.WriteLine();
}
Console.WriteLine( "After changing two elements, the IList remains the same since it is read-only..." );
display( list );
}
public static void display( IList<String> list ) {
for ( int i = 0; i < list.Count; i++ ) {
Console.WriteLine(list[i] );
}
Console.WriteLine();
}
} आउटपुट
यह निम्नलिखित आउटपुट उत्पन्न करेगा -
Initial read-only IList... John Tom Katie Brad System.NotSupportedException Collection is read-only. After changing two elements, tthe IList remains the same since it is read-only... John Tom Katie Brad