相关疑难解决方法(0)

为什么我可以通过索引访问KeyCollection/ValueCollection中的项目,即使它没有实现IList(Of Key)?

我注意到一个奇怪的VB.NET事情.从这个问题来看,我提供了一种方法来访问字典的键和值KeysCollection以及ValuesCollection通过索引来获取第一项.我知道它只是SortedDictionary因为正常Dictionary 没有被订购(嗯,你不应该依赖它的顺序).

这是一个简单的例子:

Dim sortedDict As New SortedDictionary(Of DateTime, String)
sortedDict.Add(DateTime.Now, "Foo")

Dim keys As SortedDictionary(Of DateTime, String).KeyCollection = sortedDict.Keys
Dim values As SortedDictionary(Of DateTime, String).ValueCollection = sortedDict.Values
Dim firstkey As DateTime = keys(0)
Dim firstValue As String = values(0)
Run Code Online (Sandbox Code Playgroud)

但我很惊讶问题的提问者说它不编译,而它编译并且对我有用而没有问题:

System.Diagnostics.Debug.WriteLine("Key:{0} Value:{1}", firstkey, firstValue) ' Key:04/29/2016 10:15:23 Value:Foo
Run Code Online (Sandbox Code Playgroud)

那么为什么我可以使用它,就像有一个索引器,如果实际上没有一个in SortedDictionary(Of?TKey,?TValue).KeyCollection-class,也没有ValueCollection.两者都实现了ICollection<T>哪个是父接口IList<T>.所以你可以循环它并且它有一个Count属性,但你不能像我上面那样通过索引访问项目.

请注意,它是一个新的控制台应用程序,内部没有扩展.我也不能去索引器的定义(也没有resharper).为什么它对我有用?

旁注:它在C#中不起作用.我得到了预期的编译器错误:

无法将带有[]的索引应用于"SortedDictionary.KeyCollection"类型的表达式

var dict = new SortedDictionary<DateTime, string>(); …
Run Code Online (Sandbox Code Playgroud)

.net c# vb.net compiler-errors visual-studio-2015

10
推荐指数
1
解决办法
959
查看次数

标签 统计

.net ×1

c# ×1

compiler-errors ×1

vb.net ×1

visual-studio-2015 ×1