0

I am using a dictionary wrapper class, and I want to iterate through it using key-value pairs as seen below

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

}

but a NotImplementedExceptionis thrown because I did not implement the GetEnumerator() method.

Here is my wrapper class:

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

の値を保持するには、リストまたは辞書を内部的に実装する必要があります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 に答える