如何将值传递给构造函数? [英] how to pass values to constructor?

查看:80
本文介绍了如何将值传递给构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我是 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) //...

这篇关于如何将值传递给构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆