[英]Implementing IEnumerable.GetEnumerator() in a wrapper dictionary class
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 NotImplementedException
is thrown because I did not implement the GetEnumerator()
method. 但是
NotImplementedException
了NotImplementedException
,因为我没有实现GetEnumerator()
方法。
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();
}
}
Assuming you have no special logic that your wrapper needs during enumeration you just forward the calls on to the contained instance: 假设您在枚举过程中没有包装程序需要的特殊逻辑,则只需将调用转发到所包含的实例即可:
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();
}
You're going to need to implement a List or Dictionary internally to hold the values of your LogDictionary
. 您将需要在内部实现一个List或Dictionary来保存
LogDictionary
的值。
Without knowing what DynamicTableEntity
is I will assume it implements IDictionary<string,object>
. 在不知道什么是
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.