using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class shape
{
protected double lenth = 0;
protected double width = 0;
public double Lenth
{
set { lenth = value; }
get { return lenth; }
}
public double Width
{
set { width = value; }
get { return width; }
}
public virtual double perimeter()
{
return 0;
}
public virtual double area()
{
return 0;
}
}
class circle : shape
{
protected double r;//半径
public double R
{
set { r = value; }
get { return r; }
}
public override double perimeter()
{
return Math.PI * r*2;
}
public override double area()
{
return Math.PI * r * r;
}
}
class square:shape
{
public override double perimeter()
{
return 2 * (lenth + width);
}
public override double area()
{
return lenth * width;
}
}
class Program
{
static void Main(string[] args)
{
int x = 0;//默认矩形
int y=0;//默认周长
shape a = new shape();
circle b = new circle();
Console.Write("本应用可计算圆,矩形\n请输入图形类型:");
if (Console.ReadLine() == "圆")
{
x = 1;
b.R = double.Parse(Console.ReadLine());
}
else a.Lenth = double.Parse(Console.ReadLine());
Console.WriteLine("可计算周长,面积\n请输入计算类型");
if(Console.ReadLine() == "面积")y=1;
if (x == 1)
{
if (y == 0) Console.WriteLine( "周长为{0}",b.perimeter());
else Console.WriteLine("周长为{0}",b.area());
}
else
{
if (y == 0) Console.WriteLine("周长为{0}",a.perimeter());
else Console.WriteLine("周长为{0}", a.area());
}
}
}
}
隐藏基类成员与成员的虚拟重载的区别
隐藏基类成员 关键词:new(关键词修饰)
成员的虚拟和重载:多态性 virtual/override
区别:
“虚拟与重载在运行时会根据对象的实际类型来进行调用,而不像new关键字修饰的方法那样根据声明类型来调用”
——《c#语言程序设计基础》P139
由字面上可知,多态性是指对不同类型的派生类方法的描述。
隐藏基类成员仅适用于直接使用派生类时,隐藏基类同名方法;虚拟重载可在基类按照不同条件直接自动匹配调用相应的方法。
(不知道啥时候写的文章了,直接发出来好了)
扫描二维码关注公众号,回复:
4649780 查看本文章