问题
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.
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();
}
}
回答1:
You're going to need to implement a List or Dictionary internally to hold the values of your LogDictionary
.
Without knowing what DynamicTableEntity
is I will assume it implements 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:
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();
}
回答3:
Maybe you should derive from Dictionary (not IDictionary) and call base, instead of throwing an exception in the method.
来源:https://stackoverflow.com/questions/14584106/implementing-ienumerable-getenumerator-in-a-wrapper-dictionary-class