如何使自定义类适用于foreach用法

时间:2013-02-14 15:31:01

标签: c# foreach

KeyValuePair struct具有只读属性(Key和Value),所以我创建了一个自定义类来替换它:

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
}

1 个答案:

答案 0 :(得分:3)

如果您的班级会从KeyValuePair<TKey, TValue>实施转换运算符,那么这是可能的。

但它仍然不会按预期的方式工作,因为在循环内更改键pair的值将对dictionary没有影响。字典中的键和值将保持不变。

如果要更改字典中的值,只需使用dictionary[key] = newValue;

即可

如果您想更改密钥,我猜您真的不想要Dictionary<TKey, TValue>IEnumerable<XPair<TKey, TValue>>可能更合适 如果您确实需要字典,可以使用以下代码“更改”密钥:

var value = dictionary[key];
dictionary.Remove(key);
dictionary.Add(newKey, value);