【发布时间】: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