[英]How to create a property class in c#?
我想創建一個具有兩個屬性的類,例如key
& value
。
我想要一種方法,該方法可以根據key
給我一個value
。
那么代碼是什么呢? 我知道Hashtable
但是如何在C#中實現呢? 我可以將string
作為鍵嗎?
查看Dictionary<TKey, TValue>
類: http : //msdn.microsoft.com/zh-cn/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
Dictionary<string, T>
將完成您想要的所有操作。
使用Dictionary<string, TypeOfYourVAlue>
還有另外兩個實現。 有一個HashSet ,它用於設置操作,而KeyedCollection是一個易於序列化的哈希表。
...以及System.Collections.Specialized.NameValueCollection
,大致相當於Dictionary<string,string>
,但是允許在同一鍵值下存儲多個字符串值。 引用MSDN文檔:
此類可用於標題,查詢字符串和表單數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.