代码之家  ›  专栏  ›  技术社区  ›  Chris S

.NET 4.0中的只读列表或不可修改列表

  •  88
  • Chris S  · 技术社区  · 17 年前

    domain-driven design ?

    Java与C语言相比的少数优势之一是 Collections.unmodifiablelist(list) 方法,这在IList中似乎早就过时了<T>或列表<T>。

    使用 IEnumerable<T> 这是这个问题最简单的解决办法- ToList 可以使用并返回副本。

    6 回复  |  直到 10 年前
        1
  •  152
  •   Aleksandr Dubinsky    12 年前

    你在找什么 ReadOnlyCollection

    IList<string> foo = ...;
    // ...
    ReadOnlyCollection<string> bar = new ReadOnlyCollection<string>(foo);
    

    或

    List<string> foo = ...;
    // ...
    ReadOnlyCollection<string> bar = foo.AsReadOnly();
    

    这将创建一个只读文件 看法 ,反映对已包装集合所做的更改。

        2
  •  14
  •   d219    8 年前

    .NET4.5添加了通用 IReadOnlyList List<T> 例如

    它类似于 IReadOnlyCollection 并添加了一个 Item 索引器属性。

        3
  •  13
  •   d219    8 年前

    ReadOnlyCollection 已经在框架内?

        4
  •  11
  •   d219    8 年前

    如果列表中最常见的模式是遍历所有元素, IEnumerable<T> IQueryable<T>

        5
  •  8
  •   d219    8 年前

    在2.0中,您可以调用 AsReadOnly 获取列表的只读版本。或包装现有的 IList ReadOnlyCollection<T> 对象

        7
  •  0
  •   Rm558    5 年前

    在IEnumerable上创建一个扩展方法ToReadOnlyList(),然后

    IEnumerable<int> ints = new int[] { 1, 2, 3 };
    var intsReadOnly = ints.ToReadOnlyList();
    //intsReadOnly [2]= 9; //compile error, readonly
    

    下面是扩展方法

    public static class Utility
    {
        public static IReadOnlyList<T> ToReadOnlyList<T>(this IEnumerable<T> items)
        {
            IReadOnlyList<T> rol = items.ToList();
            return rol;
        }
    }
    

    看见 Martin's answer 也

    推荐文章