简体   繁体   English

调用派生类的非继承方法

[英]call a non inherited method of a derived class

I have these 5 classes.. One base class called Figura that is an abstract class, and 4 concrete derived classes. 我有这5个类..一个叫做Figura的基类,它是一个抽象类,还有4个具体的派生类。

类

I have to create an array of Figuras of size 8 (two Cuadrado, two Rectangulo, two Triangulo and two Circulo), so I did this: 我必须创建一个8号的Figuras数组(两个Cuadrado,两个Rectangulo,两个Triangulo和两个Circulo),所以我这样做:

Figuras[] figuras = new Figuras[8];
figuras[0] = new Cuadrado(1);
figuras[1] = new Cuadrado(2);
figuras[2] = new Rectangulo(2, 1);
figuras[3] = new Rectangulo(6, 2);
figuras[4] = new Triangulo(1, 2, 2);
figuras[5] = new Triangulo(3, 3, 4);
figuras[6] = new Circulo(1);
figuras[7] = new Circulo(4);

Then I iterate through the array to calculate the area and perimeter of every figure. 然后我遍历数组来计算每个数字的面积和周长。 The problem comes when I try to call the method calcularDiametro() that belongs only to the figure Circulo. 当我尝试调用仅属于图Circulo的方法calcularDiametro()时出现问题。 How can I do that? 我怎样才能做到这一点?

I tried the following but it doesn't work. 我尝试了以下但它不起作用。

foreach (Figuras f in figuras)
    if (f is Circulo)
        f.calcularDiametro();

Any help would be appreciated. 任何帮助,将不胜感激。

You need to cast it to a Circulo in order to call Circulo -specific methods: 你需要把它投射到Circulo才能调用Circulo特有的方法:

foreach (Figuras f in figuras) 
{
    if (f is Circulo)
        (Circulo)f.calcularDiametro();
}

Note that this is a bit wasteful because it does type-checking twice (which is a costly operation). 请注意,这有点浪费,因为它会进行两次类型检查(这是一项代价高昂的操作)。 One way to do this without that waste is to use as : 要做到这一点不浪费的一种方法是使用as

foreach (Figuras f in figuras) 
{
    Circulo circ = f as Circulo;
    if (circ != null)
    {
        circ.calcularDiametro();
    }
}

You can use as opertor and prevent additional cast and improve performance 您可以使用as算子的并防止额外的演员和提高性能

foreach (Figuras f in figuras)
{
    var c = f as Circulo;
    if (c != null)
        c.calcularDiametro();
}

You can also use OfType to get objects of specific type from your Enumerable 您还可以使用OfTypeEnumerable获取特定类型的对象

foreach (var c in figuras.OfType<Circulo>())
{
    c.calcularDiametro();
}

The other answers are technically correct yet wrong. 其他答案在技术上是正确但错误的。 Your problem is you should not initiate those calculations from outside the classes in the first place. 您的问题是您不应该首先从类外部启动这些计算。 The classes themselves should perform the calculations as needed, either in the constructor or when an external component requests the value of perimetro or diametro. 类本身应该根据需要在构造函数中执行计算,或者在外部组件请求perimetro或diametro的值时执行计算。 That is encapsulation. 这就是封装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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