如何调用数组列表集合中对象的方法



我正在做我的实验室硬件。我已经试着解决那个问题一个多小时了多态性btw类形状(三角形+矩形(三角形(ScaleneTriangle、EquilateralTriangle和RightTriangle(矩形(方形(

Java解决方案对我来说也很好。


Triangle scalene = new ScaleneTriangle(3,4,5);
Triangle equilateral= new EquilateralTriangle(3,3,3);
Triangle right = new RightTriangle(3,4,5);
Rectangle square = new Square(4);
Rectangle rectangle = new Rectangle(2,5);

List<Shape> shapes = new List<Shape>();
//All the shapes are derived classes of Shape
shapes.Add(equilateral);
shapes.Add(right);
shapes.Add(scalene);
shapes.Add(rectangle);
shapes.Add(square);
foreach (var shape in shapes)
{
if (shape is Triangle)
{
shape.        //I want to call the method of equilateral, right, scalene which are derived 
//classes of Triangle
}
else if (shape is Rectangle)
{
shape.    //I want to call the method of the rectangle(base) and square(derived)
}

}

在Java中,如果知道对象的类型,就可以强制转换对象:

if (shape instanceof Rectangle) {
Rectangle rectangle = (Rectangle) shape;
// whatever the method is called
rectangle.getWidth()
}

C#

你可能想要as:

if (shape is Triangle)
{
(shape as Triangle).GetHypotenuseLength();        
(shape as Triangle).GetSmallestCornerAngle();        
(shape as Triangle).GetTypeOfTriangle();        
}

你可以让你的生活更轻松,而不必一直使用as

if (shape is Triangle t)
{
t.GetHypotenuseLength();        
t.GetSmallestCornerAngle();        
t.GetTypeOfTriangle();      
}

请注意,这在很大程度上是反对多态性的;多态性最酷的地方是,你不会写一堆";如果它是一个三角形,那么。。如果是正方形的话"因为该代码只能处理它当时所知道的形状。如果你的伴侣添加了一个实现五边形的插件,你的代码将完全忽略它

多态性的整个想法是,你所有的形状都可以(因为它们是从具有DrawYourselfOnThisCanvasPlz(Canvas c)方法的Shape派生而来(,每个不同的形状都知道如何在画布上绘制自己,所以你可以:

foreach(Shape s in listOfShapes)
s.DrawYourselfOnThisCanvasPlz(c);

现在,如果你的绘制程序的用户将五边形添加到形状列表中,你的三角形和正方形将自己绘制,而你伴侣的五边形也将自己绘制。。。

旨在尝试并找到将所有这些视为通用形状的方法,而将而非视为您目前所知的确切形状的特定实例。。而不是CCD_ 4仅仅具有CCD_;嘿,我是一个正方形,我的两边是"三角形表示";我是一个三角形,角为。。和…的斜边"。。

在调用该方法之前,需要将其强制转换为Triangle或Rectangle。这是Java解决方案。

for (Shape shape : shapes) {
if (shape instanceof Triangle) {
((Triangle)shape).call method(s) for triangle here
} else if (shape instanceof Rectangle) {
((Rectangle)shape).call method(s) for Rectangle here
}
}

最新更新