C# में Array.AsReadOnly(T[]) मेथड निर्दिष्ट सरणी के लिए एक रीड-ओनली रैपर लौटाता है, जो रीड-ओनली ReadOnlyCollection<T> होता है।
सिंटैक्स
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
यहां, T सरणी के तत्वों का प्रकार है, जबकि array T[] एक-आयामी शून्य-आधारित सरणी है।
आइए अब Array.AsReadOnly(T[]) मेथड को लागू करने का एक उदाहरण देखें -
उदाहरण
using System;
using System.Collections.Generic;
public class Demo {
public static void Main() {
String[] arr = { "John", "Tom", "Katie", "Brad" };
// रीड-ओनली IList रैपर
IList<String> list = Array.AsReadOnly( arr );
// रीड-ओनली IList के मान प्रदर्शित करें
Console.WriteLine( "प्रारंभिक रीड-ओनली IList..." );
display( list );
// अब रीड-ओनली रैपर को बदलने का प्रयास करें
try {
list[0] = "Kevin";
list[1] = "Bradley";
}
catch ( NotSupportedException e ) {
Console.WriteLine(e.GetType());
Console.WriteLine(e.Message );
Console.WriteLine();
}
Console.WriteLine( "दो तत्वों को बदलने के बाद, IList वही रहता है क्योंकि यह रीड-ओनली है..." );
display( list );
}
public static void display( IList<String> list ) {
for ( int i = 0; i < list.Count; i++ ) {
Console.WriteLine(list[i] );
}
Console.WriteLine();
}
}
आउटपुट
यह निम्नलिखित आउटपुट देगा -
प्रारंभिक रीड-ओनली IList... John Tom Katie Brad System.NotSupportedException संग्रह रीड-ओनली है। दो तत्वों को बदलने के बाद, IList वही रहता है क्योंकि यह रीड-ओनली है... John Tom Katie Brad