【问题标题】:Prevent public List property from adding items防止公共列表属性添加项目
【发布时间】:2015-11-16 12:57:54
【问题描述】:

是否可以防止IList<> 类型的公共属性添加项目。例如,我有这个简单的代码,它将一些实例存储在一个简单的列表中:

class Program
{
    private static IList<SomeItem> items = new List<SomeItem>();

    static void Main(string[] args)
    {
        // That ok
        Items.Add(new SomeItem { OrderId = 0 });
        Items.Add(new SomeItem { OrderId = 1 });
        Items.Add(new SomeItem { OrderId = 2 });

        Console.WriteLine("Amount: {0}", items.Count);

        // This should not be possible
        OrderedList.Add(new SomeItem { OrderId = 3 });
        OrderedList.Add(new SomeItem { OrderId = 4 });

        Console.WriteLine("Amount: {0}", items.Count);
        Console.ReadLine();
    }

    public static IList<SomeItem> Items
    {
        get
        {
            return items;
        }
    }

    public static IList<SomeItem> OrderedList
    {
        get
        {
            return items.OrderBy(item => item.OrderId).ToList();
        }
    }
}

我的 API 应该公开一些属性,它返回一个有序项目列表 (OrderedList)。这一切都很好,但应该无法将项目添加到此列表中,因为它们不会存储在items 中。我应该创建自己的只读列表还是我错过了一些更好的解决方案。非常感谢!

编辑

简而言之:这应该是不可能的:OrderedList.Add(new SomeItem { OrderId = 4 });

【问题讨论】:

    标签: c# list collections


    【解决方案1】:

    如果IList&lt;T&gt;不能加,其实就是IReadOnlyList&lt;T&gt;

    public static IReadOnlyList<SomeItem> OrderedList {  
      get {
        // IList<T> implements IReadOnlyList<T>, so just return List here
        ...
      }
    }
    

    【讨论】:

    • 9 分钟后。所以让我们等待:)
    【解决方案2】:

    我建议不要发布IList&lt;T&gt;,而是将列表保留在内部,只发布IReadOnlyList&lt;T&gt;

    public static IReadOnlyList<SomeItem> OrderedList
    {
        get
        {
            return items.OrderBy(item => item.OrderId).ToList().AsReadOnly();
        }
    }
    

    您可以使用AsReadOnly 方法创建列表的只读版本。这样,您返回一个ReadOnlyCollection&lt;T&gt;,因此调用者无法将属性值转换为IList&lt;T&gt;。否则,调用者可以执行此转换并添加项目。

    【讨论】:

    • 谢谢!如果我返回IReadOnlyList,我不需要.AsReadOnly();。但是在使用var 时会有所帮助!
    • @BendEg 请查看我的最新编辑;如果您执行AsReadOnly(),则返回 ReadOnlyCollection;取决于您希望界面的安全程度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多