I'm not exactly sure how to ask this question, but basically what I want to do is access the abstract methods from IDog. Consider this:
static void Main(string[] args)
{
IDog dog = new Dog();
dog.CatchFrisbee();
dog.Speak("Bark") // error -> no implementation
Console.ReadLine();
}
public class Dog : Animal, IDog
{
public void CatchFrisbee()
{
Console.WriteLine("Dog Catching Frisbee");
}
}
public abstract class Animal : IAnimal
{
public void Speak(string sayWhat)
{
Console.WriteLine(sayWhat);
}
public void Die()
{
Console.WriteLine("No Longer Exists");
}
}
public interface IDog
{
void CatchFrisbee();
}
public interface IAnimal
{
void Die();
void Speak(string sayWhat);
}
From my static void Main, I would like to be able to call dog.Speak() but I can't because it's not implemented in IDog. I know I can easily access Speak() from my derived classes but is it possible to access it from the implemenation or would that be a bad design?
假设所有IDog
都是IAnimal
, IDog
IAnimal
声明为实现IAnimal
public interface IDog : IAnimal
You could perform a cast:
((Animal) dog).Speak("Bark");
Or take advantage of multiple interface inheritance:
public interface IDog : IAnimal
{
void CatchFrisbee();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.