在包装器字典类和包装器Key结构中实现IEnumerable.GetEnumerator()

时间:2013-03-25 15:56:59

标签: c# .net dictionary

我的结构包含在

public class Class1<TKey1> : IDictionary<TKey1, Class2>
{
    #region Private Fields
    private Dictionary<Key, Class2> _class2Manager = new Dictionary<Key, Class2>(new KeyEqualityComparer());
    #endregion

    #region Key
    protected internal struct Key
    {
        private TKey1 _TKeyValue1;

        public TKey1 TKeyValue
        {
            get { return _TKeyValue1; }
            set { _TKeyValue1 = value; }
        }
        public Key(TKey1 keyValue)
        {
            _TKeyValue1 = keyValue;
        }
        ///Other Key Code
    }
    #endregion
    ///Other Class1 Code
}

我试图在_class2Manager内模拟(实现)class1字典的字典功能。当我想实现GetEnumerator()方法时出现问题。我不确定如何将IEnumerator<KeyValuePair<Key, Class2>>返回的_class2Manager.GetEnumerator()对象转换为IEnumerator<KeyValuePair<TKey1, Class2>>

IEnumerator<KeyValuePair<TKey1, Class2>> IEnumerable<KeyValuePair<TKey1, Class2>>.GetEnumerator()
{
    IEnumerator<KeyValuePair<Key, Class2>> K = _class2Manager.GetEnumerator();
}

如何将IEnumerator<KeyValuePair<Key, Class2>>转换为IEnumerator<KeyValuePair<TKey1, Class2>>

我曾想过casting,但我认为这不是我需要做的正确转换它。

感谢任何建议,谢谢。

2 个答案:

答案 0 :(得分:1)

在您的GetEnumerator()功能代码中,您可以尝试:

foreach (KeyValuePair<Key, Class2>> entry in _MasterFrames)
    yield return new KeyValuePair<Key1, Class2>(entry.Key.TKeyValue, entry.Value);

基本上,这只会为字典中的每个条目将每个Key转换为Key1

答案 1 :(得分:0)

如果要将一系列对象从一种类型映射到另一种类型,可以使用Select

return _class2Manager.Select(pair => 
        new KeyValuePair<Key1, Class2>(pair.Key.TKeyValue, pair.Value))
    .GetEnumerator();
相关问题