我想创建一个具有两个属性的类,例如key
& value
。
我想要一种方法,它会给我一个value
基于key
.
那么代码是什么?我知道Hashtable
但是如何在 C# 中实现它?我可以有一个string
作为钥匙吗?
我想创建一个具有两个属性的类,例如key
& value
。
我想要一种方法,它会给我一个value
基于key
.
那么代码是什么?我知道Hashtable
但是如何在 C# 中实现它?我可以有一个string
作为钥匙吗?
看Dictionary<TKey, TValue>
课:http: //msdn.microsoft.com/en-us/library/xfhwa508.aspx
这是实现这一点的最佳方法(我使用 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
ADictionary<string, T>
会做你想做的一切。
采用Dictionary<string, TypeOfYourVAlue>
... 还有System.Collections.Specialized.NameValueCollection
,大致相当于Dictionary<string,string>
,但允许在同一个键值下存储多个字符串值。引用 MSDN 文档:
此类可用于标题、查询字符串和表单数据。