【问题标题】:Removing an item from a generic Dictionary?从通用词典中删除项目?
【发布时间】:2011-06-10 18:56:58
【问题描述】:

我有这个:

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&lt;string, object&gt; 总是产生 null。

【问题讨论】:

  • RadControlStates.GetStates 是如何定义的?如果as 运算符返回null,那不是你想的那样。
  • 同意。只是以为我可以将所有类型转换为“对象”,但那太愚蠢了。

标签: c# refactoring templating


【解决方案1】:

您可以为此使用非通用字典接口:

(states as IDictionary).Remove(controlID);

【讨论】:

  • 我收到以下错误:“使用泛型类型 'System.Collections.Generic.IDictionary' 时出错需要 2 个类型参数”
  • 要么添加using System.Collections;,要么明确地说System.Collections.IDictionary
  • 您有任何信息说明为什么会出现这种情况吗?我想避免以后出现类似的问题,但我不知道。
  • 泛型字典接口IDictionary&lt;TKey, TValue&gt; 不支持协方差(这没有意义),因此您需要使用泛型来获取TValue 或回退到非泛型接口。
【解决方案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);
}

【讨论】:

  • T 已在 GetStates 中用于获取正确的 SerializableDictionary。
【解决方案3】:

一种选择是在表示删除操作的方法中向下传递一个 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));

【讨论】:

  • 让我看看这个。我不完全理解代码,但我很想知道这是否是一个可行的解决方案!
猜你喜欢
  • 2012-02-21
  • 2012-08-31
  • 2011-06-16
  • 2016-03-13
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多