繁体   English   中英

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

[英]Implementing IEnumerable.GetEnumerator() in a wrapper dictionary class

我正在使用字典包装器类,并且想使用键值对进行迭代,如下所示

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

}

但是NotImplementedExceptionNotImplementedException ,因为我没有实现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();
    }
}

假设您在枚举过程中没有包装程序需要的特殊逻辑,则只需将调用转发到所包含的实例即可:

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();
    }

您将需要在内部实现一个List或Dictionary来保存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();
    }
}

也许您应该派生自Dictionary(而不是IDictionary)并调用base,而不是在方法中引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM