代码之家  ›  专栏  ›  技术社区  ›  aybe

如何防止对IReadOnlyList的更改?

  •  0
  • aybe  · 技术社区  · 7 年前

    我需要使用 IReadOnlyList<T> 作为一个返回参数,因为它最符合我的需要,但正如您在下面的示例中所看到的,如果它不是真正的只读,您仍然可以修改它包装的列表。

    using System.Collections.Generic;
    using System.Collections.Immutable;
    
    public class Test
    {
        public Test()
        {
            // return an IReadOnlyList that wraps a List, we can modify content
            var list1 = GetList1();
            if (list1 is List<Section> sections1) // can be true
            {
                sections1.Clear();
            }
    
            // return an IReadOnlyList that wraps an ImmutableArray, we cannot modify content
            var list2 = GetList2();
            if (list2 is List<Section> sections2) // never true
            {
                sections2.Clear();
            }
        }
    
        public static IReadOnlyList<Section> GetList1()
        {
            return new List<Section> {new Section()};
        }
    
        public static IReadOnlyList<Section> GetList2()
        {
            return ImmutableArray.Create(new Section());
        }
    }
    
    public struct Section
    {
    }
    

    问题:

    ImmutableArray<T> 看起来很棒,因为它是真正的只读,唯一的问题是我不想/不需要公开返回它 fully-featured class 这允许进行更改以生成副本。

    因此,我坚持回去 IReadOnlyList<T> 因为它的意图很简单,但我需要修复可能可修改的列表问题。

    问题:

    正在返回一个 不可变数组<T> 作为一个 IReadOnlyList<T> 这是正确的方法吗?

    如果没有,你能建议怎么做吗?

    1 回复  |  直到 7 年前
        1
  •  3
  •   TheGeneral    7 年前

    事实并非如此 IReadOnlyList 作品

    IReadOnlyList Interface

    这个 IReadOnlyList<T> 表示包含数字和顺序的列表 列表元素的类型是只读的。 列表元素的内容不是 保证是只读的 .

    如果你想要一个 Immutable Collection 退房

    System.Collections.Immutable Namespace

    系统。收藏。不可变名称空间包含接口和 定义不可变集合的类。

    推荐文章