A創建了一個像Mark Pim建議的類似的類;然而,我的使用泛型。 我當然不會選擇使Value屬性成爲字符串類型。
public class ListItem<TKey> : IComparable<ListItem<TKey>>
{
/// <summary>
/// Gets or sets the data that is associated with this ListItem instance.
/// </summary>
public TKey Key
{
get;
set;
}
/// <summary>
/// Gets or sets the description that must be shown for this ListItem.
/// </summary>
public string Description
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the ListItem class
/// </summary>
/// <param name="key"></param>
/// <param name="description"></param>
public ListItem(TKey key, string description)
{
this.Key = key;
this.Description = description;
}
public int CompareTo(ListItem<TKey> other)
{
return Comparer<String>.Default.Compare (Description, other.Description);
}
public override string ToString()
{
return this.Description;
}
}
這也很容易創建它是非一般的變體:
public class ListItem : ListItem<object>
{
/// <summary>
/// Initializes a new instance of the <see cref="ListItem"/> class.
/// </summary>
/// <param name="key"></param>
/// <param name="description"></param>
public ListItem(object key, string description)
: base (key, description)
{
}
}
這是最靈活的解決方案。因爲「KeyValuePair」可以用任何對象來改變。如果你使用例如「Person」作爲對象,您可以設置: comboBox1.ValueMember =「SSN」; comboBox1.DisplayMember =「Name」; – ravndal
thx會嘗試。但正確的代碼是KeyValuePair(102454,「Item1」) –
senzacionale
嗯我怎麼現在可以得到鑰匙回來。我無法讀取102454或可以嗎? – senzacionale