使用ReadOnlyCollection创建只读集合
集合 创建 只读 使用
2023-09-14 08:57:24 时间
转载:http://www.cnblogs.com/abatei/archive/2008/02/04/1064102.html
使用泛型创建只读集合
问题
您希望类中的一个集合里的信息可以被外界访问,但不希望用户改变这个集合。
解决方案
使用ReadOnlyCollection<T>包装就很容易实现只读的集合类。例子如,Lottery类包含了中奖号码,它可以被访问,但不允许被改变:
public class Lottery
{
// 创建一个列表.
List<int> _numbers = null;
public Lottery()
{
// 初始化内部列表
_numbers = new List<int>(5);
// 添加值
_numbers.Add(17);
_numbers.Add(21);
_numbers.Add(32);
_numbers.Add(44);
_numbers.Add(58);
}
public ReadOnlyCollection<int> Results
{
// 返回一份包装后的结果
get { return new ReadOnlyCollection<int>(_numbers); }
}
}
{
// 创建一个列表.
List<int> _numbers = null;
public Lottery()
{
// 初始化内部列表
_numbers = new List<int>(5);
// 添加值
_numbers.Add(17);
_numbers.Add(21);
_numbers.Add(32);
_numbers.Add(44);
_numbers.Add(58);
}
public ReadOnlyCollection<int> Results
{
// 返回一份包装后的结果
get { return new ReadOnlyCollection<int>(_numbers); }
}
}
Lottery有一个内部的List<int>,它包含了在构造方法中被填的中奖号码。有趣的部分是它有一个公有属性叫Results,通过返回的ReadOnlyCollection<int>类型可以看到其中的中奖号码,从而使用户通过返回的实例来使用它。
如果用户试图设置集合中的一个值,将引发一个编译错误:
Lottery tryYourLuck = new Lottery();
// 打印结果.
for (int i = 0; i < tryYourLuck.Results.Count; i++)
{
Console.WriteLine("Lottery Number " + i + " is " + tryYourLuck.Results[i]);
}
// 改变中奖号码!
tryYourLuck.Results[0]=29;
//最后一行引发错误:// Error 26 // Property or indexer
// 'System.Collections.ObjectModel.ReadOnlyCollection<int>.this[int]'
// cannot be assigned to -- it is read only
// 打印结果.
for (int i = 0; i < tryYourLuck.Results.Count; i++)
{
Console.WriteLine("Lottery Number " + i + " is " + tryYourLuck.Results[i]);
}
// 改变中奖号码!
tryYourLuck.Results[0]=29;
//最后一行引发错误:// Error 26 // Property or indexer
// 'System.Collections.ObjectModel.ReadOnlyCollection<int>.this[int]'
// cannot be assigned to -- it is read only
讨论
ReadOnlyCollection的主要优势是使用上的灵活性,可以在任何支持IList或IList<T>的集合中把它做为接口使用。ReadOnlyCollection还可以象这样包装一般数组:
int [] items = new int[3];
items[0]=0;
items[1]=1;
items[2]=2;
new ReadOnlyCollection<int>(items);
items[0]=0;
items[1]=1;
items[2]=2;
new ReadOnlyCollection<int>(items);
这为类的只读属性的标准化提供了一种方法,并使得类库使用人员习惯于这种简单的只读属性返回类型。
相关文章
- Java集合系统
- C#使用集合组织相关数据
- Java实现 LeetCode 645 错误的集合(暴力)
- Java实现 蓝桥杯VIP 算法训练 集合运算
- 各种集合的集合
- clisp 的集合
- .NET/C#中对自定义对象集合进行自定义排序的方法
- java集合框架02——Collection架构与源码分析
- 10颜色控件-07样式面板集合-colorstyle
- Spark创建RDD的四种方式(一):从集合(内存)中创建 RDD代码示例
- MongoDB 创建大量集合测试问题
- DL之GAN&DCGNN&cGAN:GAN&DCGNN&cGAN算法思路、关键步骤的相关配图和论文集合
- DL:深度学习算法(神经网络模型集合)概览之《THE NEURAL NETWORK ZOO》的中文解释和感悟(四)
- java笔记:流式编程 数组与List集合互转
- 【Groovy】集合声明与访问 ( 使用 [] 创建 ArrayList 和 LinkedList 集合 | 集合赋初值 | 使用下标访问集合 | 使用 IntRange 作为下标访问集合 )
- JavaSE学习总结(七)—— 集合
- 今天聊聊 SQL 中的集合
- 操作系统选择题集合(一)