I want to implement a IEnumerator. But It causes a error
public class WachableDictionaryEnumerator : IEnumerator<TVal>
{
private TVal[] a;
private int len;
public bool MoveNext()
{
len = len + 1;
return len < a.Length;
}
public object Current
{
get
{
return a[len];
}
}
public TVal Current
{
get
{
return a[len];
}
}
public void Dispose()
{
a = null;
len = 0;
}
public void Reset()
{
len = 0;
}
}
The error is:
Error 5 The type 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator' already contains a definition for 'Current' D:\CE\Supins\Cyan Pembuat Soal\Required Manipulation\Class1.cs 32 25 Required Manipulation
But if I delete one of Current object, then the error is
Error 21 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator' does not implement interface member 'System.Collections.Generic.IEnumerator.Current'. 'CPS.Manipulation.WatchableDictionary.WachableDictionaryEnumerator.Current' cannot implement 'System.Collections.Generic.IEnumerator.Current' because it does not have the matching return type of 'TVal'. D:\CE\Supins\Cyan Pembuat Soal\Required Manipulation\Class1.cs 16 22 Required Manipulation
Help me to fix the code.
You need to use explicit interface implementation for one of either IEnumerator.Current or IEnumerator<T>.Current. Typically you implement the non-generic interface explicitly (where you need to), and make that implementation delegate to the generic one:
// Explicit interface implementation
object IEnumerator.Current { get { return Current; } }
// Normal implementation
public TVal Current { get { return a[len]; } }
Note that in order to get the first element correctly, you should initialize len to -1 to start with (and on Reset)... and ideally validate len in the Current property.
Note that when implementing IEnumerable<T> you need to do the same thing, e.g.
public IEnumerator<string> GetEnumerator()
{
// Whatever
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With