首页 新闻 会员 周边

用new隐藏基类方法的小疑问

0
悬赏园豆:20 [已解决问题] 解决于 2010-08-06 16:52

问题的完整代码在最下面

Temp这个派生类中

 

 

   public void A()
{
Console.WriteLine("Temp.A");
}

public void AV()
{
Console.WriteLine("Temp.AV");
}

这两个方法加不加new有何区别

不加的话也是把基类TempBase对应的方法给隐藏掉了(在我看来是这样的,貌似)

 

如果真的是这样,有没有new

就是代码规范上的问题了 

 

 

TempBase类中AV()这个方法是虚拟的,规范上 可以直接隐藏掉吗(用new或直接不写new,像上面的代码那样)

 

编译后,VS是有提示“如果是有意隐藏,请使用关键字 new”  “若要使当前成员重写该实现,请添加关键字 override。否则,添加关键字 new”... 

关键我想知道这里面的区别和知识点...   我初学不久,听听前辈几句简单的概括,应该受益匪浅...XXXDDD

 

ALL
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
TempBase tempBase
= new TempBase();
Temp temp
= new Temp();
TempBase tb
= temp;

while (true)
{
tempBase.A();
tempBase.AV();
tempBase.B();
tempBase.BV();

temp.A();
temp.AV();
temp.B();
temp.BV();

tb.A();
tb.AV();
tb.B();
tb.BV();
}
}
}

class TempBase
{
public void A()
{
Console.WriteLine(
"TempBase.A");
}

public virtual void AV()
{
Console.WriteLine(
"TempBase.AV");
}

public void B()
{
Console.WriteLine(
"TempBase.B");
}

public virtual void BV()
{
Console.WriteLine(
"TempBase.BV");
}
}

class Temp : TempBase
{
public void A()
{
Console.WriteLine(
"Temp.A");
}

public void AV()
{
Console.WriteLine(
"Temp.AV");
}

public new void B()
{
Console.WriteLine(
"Temp.B");
}

public override void BV()
{
Console.WriteLine(
"Temp.BV");
}
}
}

 

 

 

biga的主页 biga | 初学一级 | 园豆:180
提问于:2010-08-06 15:31
< >
分享
最佳答案
0

确实隐藏了,加不加其实效果一样。加就是为了语意明确。没有什么别的区别。调用基类的方法。base.方法名。

收获园豆:10
邢少 | 专家六级 |园豆:10926 | 2010-08-06 15:59
其他回答(3)
0

确实是这样的,加new是为了语意明确,多注意override就行了。

fangjie008 | 园豆:205 (菜鸟二级) | 2010-08-06 15:42
0

Temp如果要写TempBase存在的方法,加么加override或者new。如果想voerride,TempBase必须是virtual。

收获园豆:10
Astar | 园豆:40805 (高人七级) | 2010-08-06 15:44
0

我的理解是new是覆盖了父类的方法,当用父类的引用去调用这个方法时,调用的还是父类的方法,当用子类的引用调用这个方法时,调用的则是子类的方法。

Michelle 米雪儿 | 园豆:209 (菜鸟二级) | 2010-08-06 16:24
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册