[英]Removing an item from a generic Dictionary?
我有這個:
public static void Remove<T>(string controlID) where T: new()
{
Logger.InfoFormat("Removing control {0}", controlID);
T states = RadControlStates.GetStates<T>();
//Not correct.
(states as SerializableDictionary<string, object>).Remove(controlID);
RadControlStates.SetStates<T>(states);
}
states 將始終是帶有字符串鍵的 SerializableDictionary。 值的類型各不相同。 有沒有辦法表達這個? 轉換為SerializableDictioanry<string, object>
總是產生 null。
您可以為此使用非通用字典接口:
(states as IDictionary).Remove(controlID);
一種選擇是將值的類型設為通用參數:
public static void Remove<TValue>(string controlID)
{
Logger.InfoFormat("Removing control {0}", controlID);
SerializableDictionary<string,TValue> states =
RadControlStates.GetStates<SerializableDictionary<string,TValue>>();
states.Remove(controlID);
RadControlStates.SetStates<SerializableDictionary<string,TValue>>(states);
}
一種選擇是在表示刪除操作的方法中向下傳遞 lambda。 例如
public static void Remove<T>(
string controlID,
Action<T, string> remove) where T: new()
{
Logger.InfoFormat("Removing control {0}", controlID);
T states = RadControlStates.GetStates<T>();
remove(states, controlID);
RadControlStates.SetStates<T>(states);
}
然后在調用站點傳入相應的 lambda
Remove<SerializableDictionary<string, TheOtherType>>(
theId,
(dictionary, id) => dictionary.Remove(id));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.