首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用开闭原理C#计算面积

如何用开闭原理C#计算面积
EN

Stack Overflow用户
提问于 2019-12-15 23:25:40
回答 1查看 536关注 0票数 1

我正在使用C#中的SOLID的开闭原理。我有一个抽象的类形状,我想用它来计算不同形状的面积。如何调用areaCalculator类以及如何传递不同的形状。这是我的代码。

代码语言:javascript
运行
复制
public abstract class Shape
{
    public  abstract double Area();
}

public class Rectangle : Shape
{
    public double Height { get; set; }
    public double Width { get; set; }
    public override double Area()
    {
        return Height * Width;
    }
}

public class AreaCalculator
{
    public double TotalArea(Shape[] shapes)
    {
        double area = 0;
        foreach (var objShapes in shapes)
        {
            area += objShapes.Area();
        }
        return area;
    }
}

我想调用areaCalculator类来计算面积。

代码语言:javascript
运行
复制
AreaCalculator _obj = new AreaCalculator();
            Shape[] _shapes = new Shape[2];
            var _result = _obj.TotalArea(_shapes);
            Console.WriteLine(_result);
            Console.ReadLine();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-16 00:33:40

您需要创建rectangle对象,并为计算设置它们的高度和宽度。如果不是,则_shapes列表为空。在下面找到一个工作代码的示例。

代码语言:javascript
运行
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShapesStacjOverflow {


    public abstract class Shape {
        public abstract double Area();
    }

    public class Rectangle : Shape {
        public double Height { get; set; }
        public double Width { get; set; }
        public override double Area() {
            return Height * Width;
        }
    }

    public class AreaCalculator {
        public double TotalArea(Shape[] shapes) {
            double area = 0;
            foreach (var objShapes in shapes) {
                area += objShapes.Area();
            }
            return area;
        }
    }
    class Program {
        static void Main(string[] args) {
            AreaCalculator _obj = new AreaCalculator();
            Shape[] _shapes = new Shape[2];
            Rectangle rectangle1 = new Rectangle {
                Width = 2,
                Height = 3
            };
            Rectangle rectangle2 = new Rectangle {
                Width = 1,
                Height = 1
            };
            _shapes[0] = rectangle1;
            _shapes[1] = rectangle2;

            var _result = _obj.TotalArea(_shapes);
            Console.WriteLine(_result);
            Console.ReadLine();
        }
    }
}

结果返回7。如果要创建其它子形状,这些子形状应覆盖Area()方法,因此对于列表中创建的每个对象,都将应用相应的Area()方法。希望这能有所帮助。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59345298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档