繁体   English   中英

从通用词典中删除项目?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM