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:
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.