0

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

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

}

但是NotImplementedException由于我没有实现该GetEnumerator()方法,所以抛出了 a 。

这是我的包装类:

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

3 回答 3

4

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

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();
    }
于 2013-01-29T13:36:15.100 回答
3

您将需要在内部实现 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();
    }
}
于 2013-01-29T13:38:54.660 回答
1

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

于 2013-01-29T13:33:13.817 回答