Explicit virtual interfaces

  • Thread starter Thread starter amaca
  • Start date Start date
A

amaca

This does what I expect (as it should, it's from Hoffman and Kruger's C#
Unleashed):

public interface ISpeak
{
void Speak();
}

public abstract class Animal : ISpeak
{
public abstract void Speak();
}

public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine( "Woof" );
}
}

public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine( "Meow" );
}
}


that is, it allows me to define an interface, implement it in a base class
as an abstract method, and then override that method in an inherited class.
But I need to implement two interfaces with the same signature, and this
doesn't compile:

public interface ISpeak
{
void Speak();
}

public abstract class Animal : ISpeak
{
abstract void ISpeak.Speak(); // abstract not allowed
}

class Dog : Animal, ISpeak
{
override void ISpeak.Speak() // override not allowed
{
Console.WriteLine( "Woof" );
}
}

public class Cat : Animal
{
public override void Speak()
{
Console.WriteLine( "Meow" );
}
}

Is this simply not allowed (in which case why not?) or is there some arcane
syntax to allow this?

TIA

Andrew
 
amaca wrote:

But I need to implement two interfaces with the same signature, and this
doesn't compile:

Do you want to use the same implementation for both interfaces? If so,
I'd create a new abstract method in the base class (eg SpeakImpl) and
implement the two interfaces in a way which calls SpeakImpl.

Jon
 
Do you want to use the same implementation for both interfaces? If so,
I'd create a new abstract method in the base class (eg SpeakImpl) and
implement the two interfaces in a way which calls SpeakImpl.

Actually no, but it does seem the obviously easy way to go, so I'll do that.
Thanks.

Andrew
 
Hi,

You will need to use explicit declaration:

public interface ISpeak{ void A();}

abstract class C1:ISpeak
{
public abstract void A();

void ISpeak.A()
{
}

}
class C2:C1, ISpeak
{
public override void A()
{

}

void ISpeak.A()
{
}

}
 
Back
Top