Implementing IEnumerable<T> in as abstract

A

Adam Clauss

I am developing an abstract class which implements IEnumerable<T>. I need
the actual implemented methods here to be abstract as well - they will be
implemented by MY subclasses.

However, I cannot seem to get the explicit interface method to accept being
abstract.

Take the following simple class:

abstract class TestEnumerable : IEnumerable<string>
{
public abstract IEnumerator<string> GetEnumerator();

abstract IEnumerator System.Collections.IEnumerable.GetEnumerator();
}

When compiling, I get "The modifier 'abstract' is not valid for this item."
on the second GetEnumerator. Any ideas?
 
J

Jesse McGrew

Since IEnumerator<string> derives from the non-generic IEnumerator
interface, and you already have an abstract method that returns the
generic enumerator, you can just write a simple implementation for the
second version instead of making it abstract:

public abstract IEnumerator<string> GetEnumerator();

IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

Jesse
 
A

Adam Clauss

Huh... wow.

Yeah... I guess I hadn't gotten as far as thinking how I would ACTUALLY
implement the two methods yet :) Only that it would be determined by
subclasses.

Thanks for pointing out the easy-way-out!
 
J

Joanna Carter [TeamB]

"Adam Clauss" <[email protected]> a écrit dans le message de [email protected]...

|I am developing an abstract class which implements IEnumerable<T>. I need
| the actual implemented methods here to be abstract as well - they will be
| implemented by MY subclasses.
|
| However, I cannot seem to get the explicit interface method to accept
being
| abstract.
|
| Take the following simple class:
|
| abstract class TestEnumerable : IEnumerable<string>
| {
| public abstract IEnumerator<string> GetEnumerator();
|
| abstract IEnumerator
System.Collections.IEnumerable.GetEnumerator();
| }
|
| When compiling, I get "The modifier 'abstract' is not valid for this
item."
| on the second GetEnumerator. Any ideas?

Assuming that you want to use explicit interface implementation to hide any
public methods, then you can do the following :

abstract class TestEnumerable : IEnumerable<string>
{
protected abstract IEnumerator<string> GetEnumerator();

IEnumerator IEnumerable<string>.GetEnumerator()
{
return GetEnumerator();
}
}

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top