4.9 create a read-only set Using Generics
Problem
You want the information in a set in the class to be accessed by the outside world, but you do not want the user to change the set.
Solution
Using ReadOnlyCollection <T> to package, you can easily implement read-only collection classes. For example, the Lottery class contains a winning number, which can be accessed but cannot be changed:
Public class Lottery
{
// Create a list.
List <int> _ numbers = null;
Public Lottery ()
{
// Initialize the 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
{
// Return the result of a package.
Get {return new ReadOnlyCollection <int> (_ numbers );}
}
}
Lottery has an internal List <int>, which contains the winning number entered in the constructor. The interesting part is that it has a public attribute called Results. The returned ReadOnlyCollection <int> type shows the winning number, so that users can use it through the returned instance.
If you try to set a value in the Set, a compilation error is thrown:
Lottery tryYourLuck = new Lottery ();
// Print the result.
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;
// The Last Row triggers an Error: // Error 26 // Property or indexer
// 'System. Collections. ObjectModel. ReadOnlyCollection <int>. this [int]'
// Cannot be assigned to -- it is read only
Discussion
The main advantage of ReadOnlyCollection is its flexibility. It can be used as an interface in any collection that supports IList or IList <T>. ReadOnlyCollection can also Wrap general arrays 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 read-only attributes of a class, and makes the class library user accustomed to this simple read-only attribute return type.