我有这个:
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。
发布于 2011-06-11 03:04:13
您可以使用非通用字典接口来实现这一点:
(states as IDictionary).Remove(controlID);
发布于 2011-06-11 03:01:21
一种选择是将值的类型设为泛型参数:
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);
}
发布于 2011-06-11 03:01:15
一种选择是在方法中向下传递一个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));
https://stackoverflow.com/questions/6310866
复制相似问题