using System;
using System.Collections.Generic;
using System.Text;namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Windows[] my = new Windows[3];
my[2] = new Button(5, 6, "\"Button\'"); my[2].DrawWindows();
Button you = new Button(5, 6, "\"Button\'");
you.DrawWindows();
}
} class Windows
{
public Windows(int top, int left)
{
this.top = top;
this.left = left;
}
public virtual void DrawWindows()
{
Console.WriteLine("{0},{1}",top,left);
}
private int top, left;
} class ListBox : Windows
{
public ListBox(int top, int left, string listBoxStr)
: base(top, left)
{
this.listBoxStr = listBoxStr;
}
public new void DrawWindows()
{
base.DrawWindows();
Console.WriteLine("ListBox Lable :{0}", listBoxStr);
}
private string listBoxStr;
} class Button : Windows
{
public Button(int top, int left, string buttonStr)
: base(top, left)
{
this.buttonStr = buttonStr;
}
public new void DrawWindows()
{
base.DrawWindows();
Console.WriteLine("Button Lable:{0}", buttonStr);
}
private string buttonStr;
}
}这是我写的一个简单例子,大家可以跑一下。
我的疑问是:
1.用数组方式生成的button实例和直接生成的button实例 其运行期结果是不同的 这是为什么?
2.上例中,把继承类中的方法关键字(方法和基类方法同名)换成 override则运行期结果一致
3.关键字 new 和 override 到底会有什么不一样的结果?还是只是看上去清晰,在我的理解看来就算不用virtrul方法一样可以完成所有的例子,只是变异的时候会有一个警告而已。但型行期结果一致,继承类中的同名方法会屏蔽掉基类中的方法。这是些概念上的问题,不是大问题全困扰我一天了。请大家知道一二...谢谢;)
using System.Collections.Generic;
using System.Text;namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Windows[] my = new Windows[3];
my[2] = new Button(5, 6, "\"Button\'"); my[2].DrawWindows();
Button you = new Button(5, 6, "\"Button\'");
you.DrawWindows();
}
} class Windows
{
public Windows(int top, int left)
{
this.top = top;
this.left = left;
}
public virtual void DrawWindows()
{
Console.WriteLine("{0},{1}",top,left);
}
private int top, left;
} class ListBox : Windows
{
public ListBox(int top, int left, string listBoxStr)
: base(top, left)
{
this.listBoxStr = listBoxStr;
}
public new void DrawWindows()
{
base.DrawWindows();
Console.WriteLine("ListBox Lable :{0}", listBoxStr);
}
private string listBoxStr;
} class Button : Windows
{
public Button(int top, int left, string buttonStr)
: base(top, left)
{
this.buttonStr = buttonStr;
}
public new void DrawWindows()
{
base.DrawWindows();
Console.WriteLine("Button Lable:{0}", buttonStr);
}
private string buttonStr;
}
}这是我写的一个简单例子,大家可以跑一下。
我的疑问是:
1.用数组方式生成的button实例和直接生成的button实例 其运行期结果是不同的 这是为什么?
2.上例中,把继承类中的方法关键字(方法和基类方法同名)换成 override则运行期结果一致
3.关键字 new 和 override 到底会有什么不一样的结果?还是只是看上去清晰,在我的理解看来就算不用virtrul方法一样可以完成所有的例子,只是变异的时候会有一个警告而已。但型行期结果一致,继承类中的同名方法会屏蔽掉基类中的方法。这是些概念上的问题,不是大问题全困扰我一天了。请大家知道一二...谢谢;)
如果这个x 是虚函数,而且在button中重载了,那么这个drawwindows就是button中的函数,否则就不是。
而这一例子的基础是建立在用子类对象加框成基类对象的,目的是实现用基类句柄调用子类方法,以实现重载的多形性.
如果想调用子类的new方法,用子类的句柄(绝对不能用基类句柄)来调用.用new是在为子类定义方法名时,实在没有办法定义方法名的情况才与基类的方法相同,但这个方法只在子类中起到作用,而不影响基类的方法.也就是说,new方法就是子类新定义的方法.用override是直正意义上的重载.
you.DrawWindows()调用的是子类的DrawWindow方法new关键字隐藏了基类的实现
override重写基类实现
my[2] = new Button(5, 6, "\"Button\'");
虽然实例化为Button,但只有在重写虚函数时才会调用Button中的DrawWindow方法。