KeyValuePair 结构具有只读属性(键和值),所以我创建了一个自定义类来替换它:
public class XPair<T, U>
{
// members
private KeyValuePair<T, U> _pair;
// constructors
public XPair()
{
_pair = new KeyValuePair<T, U>();
}
public XPair(KeyValuePair<T, U> pair)
{
_pair = pair;
}
// methods
public KeyValuePair<T, U> pair
{
get { return _pair; }
set { _pair = value; }
}
public T key
{
get { return _pair.Key; }
set { _pair = new KeyValuePair<T, U>(value, _pair.Value); }
}
public U value
{
get { return _pair.Value; }
set { _pair = new KeyValuePair<T, U>(_pair.Key, value); }
}
}
这个类是否有可能也适用于 Dictionary 的“foreach”用法?例子:
Dictionary<String, Object> dictionary = fillDictionaryWithData();
foreach(XPair<String, Object> pair in dictionary) {
// do stuff here
}