简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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