读书人

C#的方法隐藏有关问题高手来讲一下。

发布时间: 2011-12-29 22:09:38 作者: rapoo

C#的方法隐藏问题高手来讲一下。。
public class customer{
public string getName(){
return "customer,kaar ";
}
}
class customerA:customer{
public new string getName(){
return "customerA,xiaoxiao ";

}
public static void main(string[] a){
customer c = new customerA();
console.Writeline(c.getName);
}
}
这个题的结果是 :customer,kaar
这个题不是隐藏了基类的getName()方法吗?我感觉应该打印这个customerA,xiaoxiao 才对。

customer c = new customerA(); 这句话不就是JAVA里的上转型吗,正常也应该是打印 customerA,xiaoxiao 才对。
求高手来讲讲

[解决办法]
customer c = new customerA();

实体c以customerA初始化为customer;

class customerA:customer{
public new string getName() //这里使用关键字new, return "customerA,xiaoxiao "; //这证明此继承类与基类的getName方法无关,

}


所以调用c.getName().则调用的是
public class customer{
public string getName(){
return "customer,kaar ";
}
}
方法,
[解决办法]
using System;

namespace ZZ
{
class ZZConsole
{
[STAThread]
static void Main(string[] args)
{
A a = new A();
a.Show();//你调用了A类的Show方法.
B b = new B();
b.Show();//你调用了B类的Show方法.
((A)b).Show();//你调用了A类的Show方法.
C c = new C();
c.Show();//你调用了C类的Show方法.
((A)c).Show();//你调用了C类的Show方法.
Console.ReadLine();
}

}
class A
{
public virtual void Show()
{
Console.WriteLine( "你调用了A类的Show方法. ");
}
}
class B : A
{
public new void Show()
{
Console.WriteLine( "你调用了B类的Show方法. ");
}
}
class C : A
{
public override void Show()
{
Console.WriteLine( "你调用了C类的Show方法. ");
}
}
class D : A
{
public sealed override void Show()
{
Console.WriteLine( "你调用了C类的Show方法. ");
}
}
class E : D
{
//无法重写继承的成员,因为它已被密封
//public override void Show()
//{
//Console.WriteLine( "你调用了C类的Show方法. ");
//}
//public sealed override void Show()
//{
//Console.WriteLine( "你调用了C类的Show方法. ");
//}
//隐藏基类的方法
public new void Show()
{
Console.WriteLine( "你调用了C类的Show方法. ");
}

}

}

读书人网 >C#

热点推荐