简体   繁体   English

C#和VB.Net之间的字典差异

[英]Dictionary Difference between C# and VB.Net

Why if I have a Dictionary<string, MyClass> myDic in C# I can't do myDic.Values[1] because it can't index a Dictionary instead of Vb.Net that allow me to do myDic.Values(1) ? 为什么如果我在C#中有一个Dictionary<string, MyClass> myDic我不能做myDic.Values[1]因为它不能索引允许我做myDic.Values(1)的Dictionary而不是Vb.Net? Is there any difference between C# Dictionary and a VB.Net one? C#词典和VB.Net词典之间有什么区别吗?

No, the short answer is that you cannot apply an indexing to a C# Dictionary<>.ValueCollection. 不,简短的答案是您不能将索引应用于C# Dictionary<>.ValueCollection.

As mentioned in the comments below, the closest C# correlation is using myDict.Values.ElementAtOrDefault(1) to retrieve the value, since it will safely return the default if the value is not present, which matches the VB.Net behavior. 如以下注释中所述,最接近的C#相关性使用myDict.Values.ElementAtOrDefault(1)检索值,因为如果不存在该值,它将安全地返回默认值,该值与VB.Net行为匹配。 That said, this may be indicative of misusing a dictionary, particularly since order is not guaranteed. 也就是说,这可能表示滥用字典,特别是因为不能保证顺序。

Typically, the most efficient and valuable way to retrieve values from a Dictionary is by key lookup. 通常,从字典中检索值的最有效和最有价值的方法是通过键查找。 This is merely speculation, but it wouldn't surprise me if indexing on the Values Collection was not supported in C# simply to guide you in the right direction and prevent abuse. 这仅仅是猜测,如果C#不支持在Values Collection上建立索引只是为了引导您朝正确的方向并防止滥用,也不会令我感到惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM