一位朋友最近接受了电话采访,他被问到一个技术问题:
问)如果我想计算某些2D形状的表面积,那么" Bucket"我会用吗他有20分钟写一些代码,面试官给他回电话。他通过电子邮件发送了代码,代码的其余部分没有讨论代码(没有其他技术问题)。他给我发了代码:
Windows窗体应用
namespace ShapesApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += form_load;
}
public void form_load (Object o, EventArgs e)
{
List<Shape> listShape = new List<Shape>();
Shapes.Circle circle = new Shapes.Circle();
Shapes.Rectangle rectangle = new Shapes.Rectangle();
Shapes.Square square = new Shapes.Square();
Shapes.Triangle triangle = new Shapes.Triangle();
listShape.Add(rectangle);
listShape.Add(square);
listShape.Add(triangle);
foreach (Shape shape in listShape)
{
double a = 10;
double b = 10;
double surfaceArea = shape.CalculateSurfaceArea(a,b);
Console.WriteLine("The surface area of a " + shape.GetType() + " is: " + surfaceArea);
}
}
}
}
形状 - 类库
namespace Shapes
{
public abstract class Shape
{
abstract public double CalculateSurfaceArea(double Double1, double Double2);
}
public class Circle : Shape
{
public override double CalculateSurfaceArea(double pi, double radius)
{
return (pi * radius) * (pi * radius);
}
}
public class Triangle : Shape
{
public override double CalculateSurfaceArea(double Base, double Height)
{
return (Base*Height)/2;
}
}
public class Rectangle : Shape
{
public override double CalculateSurfaceArea(double Length, double Width)
{
return Length * Width;
}
}
}
面试官说他挣扎着#34;通过测试。代码有什么问题?
答案 0 :(得分:0)
计算区域是行为,每个形状都有自己的计算公式。由于计算区域可能涉及不同数量的变量,常量方法不会采用任何参数,变量将成为实现接口的类的关注。
所以我认为计算区域的方法可以抽象为接口:
public interface ICalculatingArea
{
double CalculateArea();
}
然后每个形状都会以自己的方式实现它。
public class Rectangle:ICalculatingArea
{
public double Width {get; set;}
public double Length {get; set;}
public double CalculateArea()
{
return Length * Width;
}
}
在主程序中,将形状类强制转换为接口类型并使用CalculateArea
方法