在包装字典类中实现 IEnumerable.GetEnumerator()

本文关键字:IEnumerable GetEnumerator 实现 包装 字典 | 更新日期: 2023-09-27 17:56:25

>我正在使用字典包装类,我想使用键值对遍历它,如下所示

private void LoadVariables(LogDictionary dic)
{
    foreach (var entry in dic)
    {
        _context.Variables[entry.Key] = entry.Value;
    }
}

但是抛出了一个NotImplementedException,因为我没有实现GetEnumerator()方法。

这是我的包装类:

public class LogDictionary: IDictionary<String, object>
{
    DynamicTableEntity _dte;
    public LogDictionary(DynamicTableEntity dte)
    {
        _dte = dte;
    }
        bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
    {
        throw new NotImplementedException();
    }
    IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
    {
        throw new NotImplementedException();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

在包装字典类中实现 IEnumerable.GetEnumerator()

假设包装器在枚举期间没有需要的特殊逻辑,您只需将调用转发到包含的实例:

public class LogDictionary: IDictionary<String, object>
{
    DynamicTableEntity _dte;
    public LogDictionary(DynamicTableEntity dte)
    {
        _dte = dte;
    }
        bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
    {
        throw new NotImplementedException();
    }
    IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
    {
        return _dte.GetEnumerator();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
您需要

在内部实现列表或字典来保存LogDictionary的值。

在不知道DynamicTableEntity是什么的情况下,我将假设它实现了IDictionary<string,object>

public class LogDictionary: IDictionary<String, object>
{
    private IDictionary<String, object> _dte;
    public LogDictionary(DynamicTableEntity dte)
    {
        _dte = (IDictionary<String, object>)dte;
    }
    bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
    {
        return _dte.Remove(item.Key);
    }
    IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
    {
        return _dte.GetEnumerator();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

也许你应该从字典(不是IDictionary)和调用库派生,而不是在方法中抛出异常。