【发布时间】:2015-01-20 01:15:45
【问题描述】:
我最初有一些代码,简化后看起来像这样:
var planets = new List<Planet>
{
new Planet {Id = 1, Name = "Mercury"},
new Planet {Id = 2, Name = "Venus"},
};
我遇到了这样一个场景:列表被一次全部填充,但读取速度不够快。因此,我将其更改为使用 SortedList。
后来我意识到我可以这样重写它
var planets = new SortedList<int, Planet>
{
{1, new Planet {Id = 1, Name = "Mercury"}},
{2, new Planet {Id = 2, Name = "Venus"}},
//in my actual code, i am reading the ids from a db
};
但在我采用这种方法之前,我的代码是这样写的
var planets = new SortedList<int, Planet>
{
Keys = {1, 2},
Values =
{
new Planet {Id = 1, Name = "Mercury"},
new Planet {Id = 2, Name = "Venus"},
}
};
这给了我这个例外
System.NotSupportedException: This operation is not supported on SortedList
nested types because they require modifying the original SortedList.
at System.ThrowHelper.ThrowNotSupportedException(ExceptionResource resource)
at System.Collections.Generic.SortedList`2.KeyList.Add(TKey key)
我觉得这很奇怪,因为恕我直言,我并没有真正修改它声称的“原始 SortedList”,它在谈论什么“嵌套类型”?它是SortedList 内部的键列表吗?
然后我看到SortedList 中的Keys 和Values 属性实际上没有设置器。它们是只读属性,但是,我没有收到编译时错误。我可以进行 set 调用,正如我在堆栈跟踪中看到的 KeyList.Add。我觉得这失败的唯一原因是因为在SortedList 中进行了明确的检查,这对我来说似乎很奇怪!
例如
var str = new String {Length = 0}; 按预期给我一个编译时错误,因为 Length 是一个只读属性,planets.Keys = null; 也是如此
请告诉我 - 我在这里忽略了什么简单的事实?
【问题讨论】:
标签: c# .net setter sortedlist