C#的只读集合的创建、用途

勇哥注:

我们知道C#的集合有两类

  • 普通集合

  • 泛型集合

前者存在于 System.Collections 命名空间下,属类型不安全的,后者存在于 System.Collections.Generic 命名空间下,属类型安全的。

不可变对象也就是本文说的只读对象, 定义为一旦创建就不可变更的对象, 在 .NET Core 中就存在着这三大不可变集合

IReadOnlyList

IReadOnlyDictionary

IReadOnlyCollection 


简单示例:

internal ReadOnlyCollection<ButtonItem> buttonItems { get { return _buttonItems.AsReadOnly(); } }
private List<ButtonItem> _buttonItems = new List<ButtonItem>();

其中ReadOnlyCollection就是泛型只读集合的基类,它的原型如下:

    //
    // 摘要:
    //     提供泛型只读集合的基类。
    //
    // 类型参数:
    //   T:
    //     集合中的元素类型。
    [ComVisible(false)]
    [DebuggerDisplay("Count = {Count}")]
    [DebuggerTypeProxy(typeof(Generic.Mscorlib_CollectionDebugView<>))]
    [DefaultMember("Item")]
    public class ReadOnlyCollection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, 
        IReadOnlyList<T>, IReadOnlyCollection<T>

可以看到,它即继承接口IReadOnlyList,还继承接口IReadOnlyCollection 


在真正的项目实践中,有时为了数据安全,我们经常要对集合做一些限制,如只能对集合里面的内容进行读取,但不能修改,

这时我们可有使用ReadOnlyCollection<T>来对集合做一些限制,例如:

public class Lottery
{
  List<int> _numbers = null;

  public Lottery()
  {
    _numbers = new List<int>(5);

    _numbers.Add(10);
    _numbers.Add(21);
    _numbers.Add(32);
    _numbers.Add(46);
    _numbers.Add(51);

  }


  public ReadOnlyCollection<int> Results
  {
    get
    {
      return new ReadOnlyCollection<int>(_numbers);
    }
  }
}

static void Main(string[] args)
{
  Lottery ttery = new Lottery();

  foreach (int list in ttery.Results)
  {
    Console.WriteLine(list);
  }

  ttery.Results[0] = 1;//这行代码在编译器里面会提示错误,因为Results是只读的
}

 

当然,上述我们讲的都是list,那ReadOnlyCollection<int>也同样适用于数组,如下:

int [] items = new int[3];
items[0]=0;
items[1]=1;
items[2]=2;

new ReadOnlyCollection<int>(items);

注:在使用时,需要添加using System.Collections.ObjectModel 这个引用。




本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年5月    »
12345
6789101112
13141516171819
20212223242526
2728293031
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864