Reprint: http://www.cnblogs.com/abatei/archive/2008/02/04/1064102.html
Create a read-only collection using generics
Problem
You want the information in a collection in a class to be accessible to the outside world, but you do not want the user to change the collection.
Solution Solutions
It is easy to implement a read-only collection class using the Readonlycollection<t> wrapper. For example, the lottery class contains the winning number, which can be accessed but not allowed to be changed:
public class Lottery
{
Create a list.
List<int> _numbers = null;
Public lottery ()
{
Initialize internal list
_numbers = new list<int> (5);
Add Value
_numbers. ADD (17);
_numbers. ADD (21);
_numbers. ADD (32);
_numbers. ADD (44);
_numbers. ADD (58);
}
Public readonlycollection<int> Results
{
Returns a copy of the result after packing
get {return new readonlycollection<int> (_numbers);}
}
}
The lottery has an internal list<int>, which contains the winning numbers that are filled in the construction method. The interesting part is that it has a public property called results, which can be seen by the returned readonlycollection<int> type, allowing the user to use it through the returned instance.
If a user attempts to set a value in the collection, a compilation error is raised:
Lottery Tryyourluck = new Lottery ();
Print the results.
for (int i = 0; i < TryYourLuck.Results.Count; i++)
{
Console.WriteLine ("Lottery Number" + i + "is" + tryyourluck.results[i]);
}
Change the winning number!
tryyourluck.results[0]=29;
Last line throws an error://error//property or indexer
' System.collections.objectmodel.readonlycollection<int>.this[int] '
cannot be assigned to--it's read only
Discuss
The main advantage of ReadOnlyCollection is the flexibility of use, which can be used as an interface in any collection that supports IList or ilist<t>. ReadOnlyCollection can also wrap a generic array like this:
int [] items = new Int[3];
items[0]=0;
Items[1]=1;
items[2]=2;
New readonlycollection<int> (items);
This provides a way to standardize the class's read-only properties and makes the class library user accustomed to this simple read-only property return type.
Create a read-only collection using ReadOnlyCollection