[英]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
给定一个类Animal
和派生自Animal
的两个类Cat
和Dog
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?调用构造函数后,在这个xxx
类中,我希望能够执行animal.catMethod1()
如果它被分配给Cat
和animal.dogMethod3()
如果它被分配给Dog
,这可能吗?
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 . 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.我认为这不是一个好的做法(不是 liskov 替换),但你可以。
(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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.