简体   繁体   中英

Calling Method of subclass over interface without implementing the method there

I have the interface IPet and in another project I have the class Dog which inherits from IPet .
In Dog I have the method Bark() but not in IPet .
In the project of IPet I have also the class PetSimulation in which I have an instance of IPet .
Now I want to make something like this:

IPet myDog = new IPet("Rex");  
myDog.Bark();  

But IPet does not have the method Bark() and that should remain that way because other classes such as Cat and Horse are also inherit from IPet but don't have the method Bark either.
Also I can't do something like this:

Dog myDog = new Dog("Rex");  

because Dog is in another project.

Is there any way for me to call the Method Bark of the subclass Dog over the interface IPet without implementing the method there?

Short answer: No.

Slightly longer answer:

You can test the IPet to see if it is a Dog , like this:

Dog dog = myDog as Dog;
if (dog != null)
{
    dog.Bark();
}

Note that you can't directly create an interface like you do in the question, except in very rare circumstances .

You cant. But you could make an interface IDog with the method Bark, that would inherit from IPet

public interface IPet
{

}

public interface IDog : IPet
{
    void Bark();    
}

public class Dog : IDog
{
    public void Bark()
    {
        Console.WriteLine("Wouff!");    
    }
}

You would need to cast myDog to Dog in order to access methods that only that class has:

IPet myDog = new IPet("Rex");  
((Dog)myDog).Bark();  

If you implement Bark in the interface then it will be required for all classes that implement it.

Can you access Dog by adding a reference to Dog's project?

If you really cannot access the Dog class and are working in .NET 4+ you could try

dynamic dog = new ...
dog.Bark()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM