如何将值传递给构造函数

本文关键字:构造函数 值传 | 更新日期: 2023-09-27 18:26:26

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

我是OOP的新手,正在学习以下代码。

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件事:

  1. 如何在设计时传递值
  2. 如何在运行时传递值(当两个参数都可以是任何类型时)
  3. 如何在这里以OO方式进行验证

谢谢你的时间和帮助。

如何将值传递给构造函数

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

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());

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

你可以做一些类似的事情

if (shape1 is Circle) //...

只需执行类似的操作

SwimmingPool(IShape innerShape, IShape outerShape)
{
    this.innerShape = innerShape;
    this.outerShape = outerShape;
    this.Validate();
}
private void Validate()
{
     // or some other condition
     if ( GetRequiredArea() < 0 ){
          throw new Exception("The outer shape must be greater than the inner one");
     }
}