Java Map等价于C# [英] Java Map equivalent in C#
问题描述
我想使用我选择的键保存集合中的项目列表。在Java中,我将简单地使用Map如下:
class Test {
Map< Integer,String&实体;
public String getEntity(Integer code){
return this.entities.get(code);
}
}
在C#中有同样的方法吗?
System.Collections.Generic.Hashset
不使用哈希,我不能定义自定义类型键
System.Collections .Hashtable
不是通用类
System.Collections.Generic.Dictionary
没有 get(Key)
方法
'get'。
字典< string,string> example = new Dictionary< string,string>();
...
example.Add(hello,world);
...
Console.Writeline(example [hello]);
测试/获取值的有效方法是 TryGetValue
(thanx to Earwicker):
if(otherExample.TryGetValue(key,out value))
{
otherExample [key] = value + 1;使用这种方法,您可以快速获取值和无异常的值(如果存在) 。
资源:
I'm trying to hold a list of items in a collection with a key of my choice. In Java, I would simply use Map as follows:
class Test {
Map<Integer,String> entities;
public String getEntity(Integer code) {
return this.entities.get(code);
}
}
Is there an equivalent way of doing this in C#?
System.Collections.Generic.Hashset
doesn't uses hash and I cannot define a custom type key
System.Collections.Hashtable
isn't a generic class
System.Collections.Generic.Dictionary
doesn't have a get(Key)
method
解决方案 You can index Dictionary, you didn't need 'get'.
Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);
An efficient way to test/get values is TryGetValue
(thanx to Earwicker):
if (otherExample.TryGetValue("key", out value))
{
otherExample["key"] = value + 1;
}
With this method you can fast and exception-less get values (if present).
Resources:
这篇关于Java Map等价于C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!