override的问题
这种重写是修改基类的执行代码吗?
------解决方案--------------------override重写是重新实现基类的方法
new 是新建的方法....
他们有什么区别?
。。。。 重写可以实现多态..
class A
{
public virtual void method();
}
class B:A
{
public override void method();
}
class main
{
public static void main()
{
A a=new B();
a.method();// 实际是调用B.method
}
}
------解决方案--------------------namespace kkun
{
class kkun
{
class MyBaseClass
{
public virtual string DoSomething()
{
return "11 ";
}
public string DoSomething2()
{
return "12 ";
}
}
class MyDerivedClass : MyBaseClass
{
public override string DoSomething()
{
return "21 ";
}
public new string DoSomething2()
{
return "22 ";
}
}
static void Main()
{
MyBaseClass aa = new MyDerivedClass();
MyBaseClass bb = new MyBaseClass();
MyDerivedClass cc=new MyDerivedClass();
System.Console.WriteLine(aa.DoSomething());//21
System.Console.WriteLine(aa.DoSomething2());//12
System.Console.WriteLine(bb.DoSomething());//11
System.Console.WriteLine(bb.DoSomething2());//12
System.Console.WriteLine(cc.DoSomething());//21
System.Console.WriteLine(cc.DoSomething2());//22
System.Console.ReadLine();
}
}
}