0

我想创建一个具有两个属性的类,例如key& value

我想要一种方法,它会给我一个value基于key.

那么代码是什么?我知道Hashtable但是如何在 C# 中实现它?我可以有一个string作为钥匙吗?

4

7 回答 7

4

Dictionary<TKey, TValue>课:http: //msdn.microsoft.com/en-us/library/xfhwa508.aspx

于 2009-03-26T11:11:43.947 回答
4

这是实现这一点的最佳方法(我使用 Int32 作为存储类型的示例):

Dictionary<String,Int32> dictionary = new Dictionary<String,Int32>
{
    // this just loads up the list with
    // some dummy data - notice that the
    // key is a string and the value is an int
    { "one", 1 },
    { "two", 2 },
    { "three", 3 },
};

现在您可以像这样从 Dictionary<,> 中获取值:

dictionary["one"]; // returns 1
dictionary["two"]; // returns 2
于 2009-03-26T11:13:06.067 回答
2

ADictionary<string, T>会做你想做的一切。

于 2009-03-26T11:12:37.330 回答
1

采用Dictionary<string, TypeOfYourVAlue>

于 2009-03-26T11:12:26.487 回答
1

字典(TKey,TValue)类

于 2009-03-26T11:14:58.247 回答
1

还有更多的实现。HashSet是为集合操作而设计的,而KeyedCollection一个易于序列化的哈希表。

于 2009-03-26T11:34:01.727 回答
1

... 还有System.Collections.Specialized.NameValueCollection,大致相当于Dictionary<string,string>,但允许在同一个键值下存储多个字符串值。引用 MSDN 文档:

此类可用于标题、查询字符串和表单数据。

于 2009-03-26T18:57:37.947 回答