从通用字典中删除项目?

时间:2011-06-10 18:56:59

标签: c# refactoring templating

我有这个:

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);
}

状态将始终是带字符串键的SerializableDictionary。值的类型各不相同。有没有办法表达这个?转换为SerializableDictioanry<string, object>始终为null。

3 个答案:

答案 0 :(得分:5)

您可以使用非通用字典界面:

(states as IDictionary).Remove(controlID);

答案 1 :(得分:2)

一个选项是将值的类型设为通用参数:

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);
}

答案 2 :(得分:1)

一种选择是在代表remove操作的方法中传递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));