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

时间:2012-03-03 02:19:49

标签: c# oop

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

我是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类的构造函数,但我没有得到如何将值传递给构造函数。我以前没有使用Interfaces编程。请指导我3件事:

  1. 如何在设计时传递值。
  2. 如何在运行时传递值(当两个参数都可以是任何类型时)。
  3. 如何以OO方式进行验证?
  4. 感谢您的时间和帮助。

2 个答案:

答案 0 :(得分:4)

做这样的事

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");
     }
}

答案 1 :(得分:4)

嗯,您正在使用接口,因此在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) //...