我正在使用字典包装器类,我想使用键值对迭代它,如下所示
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();
}
}
答案 0 :(得分: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();
}
答案 1 :(得分:2)
您需要在内部实施一个列表或词典来保存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();
}
}
答案 2 :(得分:1)
也许你应该从Dictionary(而不是IDictionary)派生并调用base,而不是在方法中抛出异常。