如何将值传递给构造函数?

问题描述:

很抱歉我的问题有点理论性

我是 OOP 的新手,正在研究以下代码.

I am new to OOP and studying the following code.

public interface IShape
{
    double getArea();
}

public class Rectangle : IShape
{
    int lenght;
    int width;        

    public double getArea()
    {
        return lenght * width;
    }       
}

public class Circle : IShape
{
    int radius;       

    public double getArea()
    {
        return (radius * radius) * (22 / 7);
    }        
}

public class SwimmingPool
{
    IShape innerShape;
    IShape outerShape;

    SwimmingPool(IShape _innerShape, IShape _outerShape)
    {
        //assignment statements and validation that poolShape can fit in borderShape;
    }

    public double GetRequiredArea()
    {
        return outerShape.getArea() - innerShape.getArea();
    }

}

此代码计算不同形状的面积.我可以看到 SwimingPool 类的构造函数,但我不知道如何将值传递给构造函数.我以前没有使用接口进行编程.请指导我 3 件事:

This code calculate area of different shapes. I can see constructor of SwimingPool class but I am not getting how to pass values to constructor. I have not done programming using Interfaces before. Please guide me 3 things:

  1. 如何在设计时传递值.
  2. 如何在运行时传递值(当两个参数都可以是任何类型时).
  3. 如何以面向对象的方式在此处进行验证?

感谢您的时间和帮助.

好吧,您正在使用接口,因此在您的 SwimmingPool 类中,构造函数将需要两个 IShape 参数.由于您需要一个实现才能使用您的界面,例如您的 RectangleCircle,您只需执行以下操作:

Well, you are using interfaces so in your SwimmingPool class, the constructor will require two IShape parameters. Since you need an implementation in order to use your interface, such as your Rectangle and Circle, you would simply do something like this:

class Pool
{
    private IShape _InnerShape;
    private IShape _OuterShape;

    public Pool(IShape inner, IShape outer)
    {
        _InnerShape = inner;
        _OuterShape = outer;
    }

    public double GetRequiredArea()
    {
        return _InnerShape.GetArea() - _OuterShape.GetArea();
    }

  }

用法类似于

IShape shape1 = new Rectangle() { Height = 1, Width = 3 };
IShape shape2 = new Circle() { Radius = 2 };

Pool swimmingPool = new Pool(shape1, shape2); 
Console.WriteLine(swimmingPool.GetRequiredArea());

根据您的评论,您似乎想测试对象是否实现了接口.

It seems, based on your comment, is that you want to test if an object implements an interface.

你可以这样做

if (shape1 is Circle) //...