开发者

Removing an item from a generic Dictionary?

I have this:

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 will always be a SerializableDictionary with string keys. The values' type vary. Is there a way to express this? Casting to SerializableDictioanry<string, object> always yields null.


You can use the non-generic dictionary interface for this:

(states as IDictionary).Remove(controlID);


One option is making the type of the value your generic parameter:

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


One option is to pass a lambda down in the method which represents the remove operation. For example

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

And then at the call site pass in the appropriate lambda

Remove<SerializableDictionary<string, TheOtherType>>(
  theId, 
  (dictionary, id) => dictionary.Remove(id));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜