谢谢各位,听起来好像重载时,原方法的一些操作可以复用。下面这个例子,如何在重载时用虚方法Area中的语句,好像重载后就不会执行return x*y了吧? using system public class Base { protected double x; protected double y; public Base() { } public Base(double x,double y) { this.x=x; this.y=y; } public virtual double Area() { return x*y; } }public class Derive:Base { public Derive(double h,double r):base(h,r) { } public override double Area() { return 2*Math.PI*y*y+2*Math.PI*x*y; } public class PolymorphismApp1 { public static void Main() { Base obj=new Base(11,17); Derive obj2=new Derive(10,25); Console.WriteLine("is:{0}",obj.Area()); Console.WriteLine("is:{0}",obj2.Area()); } } }
Base obj=new Base(11,17); Derive obj2=new Derive(10,25); Console.WriteLine("is:{0}",obj.Area()); Console.WriteLine("is:{0}",obj2.Area()); ================== 这样调用体现不出重载其实多态用武之地是在父类指向子类时,此时通过动态编译可以实现重载 Base obj = new Derive(10,25); 此时将调用Derive类的Area()方法,而不是Base类的Area()方法
“理发店”是一个被重载的方法!
private void 理发店(int intMoney,string strDemand,)
{
//
}
private void 理发店(int intMoney,string strDemand,string strAdvancedService)
{
//
}楼主理解是正确的,但貌似这样更规范!
不管是同一个类中参数不同的同名方法们(被称作重载),还是基类及其子类中的同名方法们(也被称作重载,不过 C# 中叫重写 override,还可以通过 new 来覆盖基类中的同名方法),
都是为了让阅读代码和/或使用类库的人明白这些方法有何作用,至于那些方法各自具体怎么做的,就交给他们了。
从概念上讲,通常子类都是基类的特例,基类可以做的某件事情(某个方法),子类也可以做,甚至可以做得更多更好,但子类首先要做到基类能做的,这就是为什么要 base.Method() 的缘故,当然子类也可以选择不做更多。
using system
public class Base
{
protected double x;
protected double y;
public Base()
{
}
public Base(double x,double y)
{
this.x=x;
this.y=y;
}
public virtual double Area()
{
return x*y;
}
}public class Derive:Base
{
public Derive(double h,double r):base(h,r)
{
}
public override double Area()
{
return 2*Math.PI*y*y+2*Math.PI*x*y;
}
public class PolymorphismApp1
{
public static void Main()
{
Base obj=new Base(11,17);
Derive obj2=new Derive(10,25);
Console.WriteLine("is:{0}",obj.Area());
Console.WriteLine("is:{0}",obj2.Area()); }
}
}
Derive obj2=new Derive(10,25);
Console.WriteLine("is:{0}",obj.Area());
Console.WriteLine("is:{0}",obj2.Area());
==================
这样调用体现不出重载其实多态用武之地是在父类指向子类时,此时通过动态编译可以实现重载
Base obj = new Derive(10,25);
此时将调用Derive类的Area()方法,而不是Base类的Area()方法