首页 > 开发 > 综合 > 正文

C#继承类重写与隐藏基类方法的区别

2024-07-21 02:26:17
字体:
来源:转载
供稿:网友

using system;
using system.collections;

public class nevermore60customer:customer
{
public override string getfunnystring()
{
return "nevermore60.nevenmore!";
}

 

--------------------------------------------------------------------------------

public class customer
{
public virtual string getfunnystring()
{
return "plain ordinary customer.kaark!";
}
public class samplesarray
{
public static void main()
{
customer cust1=new nevermore60customer();
nevermore60customer cust2;
// cust1=new customer();
console.writeline("customer referencing customer."+cust1.getfunnystring());
cust1=new nevermore60customer();
console.writeline("customer referencing nevenmore60customer:"+cust1.getfunnystring());
cust2=new nevermore60customer();
console.writeline("nevenmore60customer referencing"+cust2.getfunnystring());


}
}

customer cust1=new nevermore60customer();
如果是重写:则,如果声明的基类对象,指向的是派生类,那么这时调用的是派生类中对基本重写的方法的方法(如上所示)
如果是隐藏基类方法: public new string getfunnystring()
{
return "nevermore60.nevenmore!";
}
则:customer cust1=new nevermore60customer();此时cust1调用的仍是声明时候的基类中的getfunnystring方法.
但二者声明与赋值都是同一个类时,不会发生这种问题.
 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表