简体   繁体   中英

Assigning derived class to base, and using the derived methods?

I am trying to assign a derived class to a base class and then using the methods from the derived class, here is an example of what I mean.

Given a class Animal and two classes Cat and Dog that are derived from Animal

public class xxx{
    private Animal animal;

    public xxx(Cat c){
        animal=c
    }

    public xxx(Dog d){
        animal=d
    }
}

After the constructor is called, In this xxx class I want to be able to do animal.catMethod1() if it was assigned to a Cat and animal.dogMethod3() if it was assigned to a Dog , is this possible?

You may want to take a look at the factory software pattern to accomplish this:

An article here explains the Gang of Four implementation:

https://www.c-sharpcorner.com/article/factory-method-design-pattern-in-c-sharp/#:~:targetText=Factory%20Design%20Pattern%20C%23&targetText=The%2023%20Gang%20of%20Four,Four%20(GoF)%20Design%20Patterns .

I think it's not a good practice (not liskov substitution), but you can.

(animal as Cat)?.catMethod1();
(animal as Dog)?.dogMethod3();
//By Pattern Matching
switch (animal)
{
  case Cat cat:
    cat.catMethod1()
    break;
  case Dog dog:
    dog.dogMethod3()
    break;
}

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