The new keyword will block inherited methods referring to normally overridden methods.
In this case the base method will be called
public class Parent
{
public void msgShow2()
{
MessageBox.Show(this.show2());
}
public virtual string show2()
{
return "parent" + this.GetType().ToString();
}
public virtual string show()
{
return "parent" + this.GetType().ToString();
}
}
public class Child1 : Parent
{
public override string show2()
{
return "Child1:override" + this.GetType().ToString();
}
public override string show()
{
return "Child1" + this.GetType().ToString();
}
public void message()
{
MessageBox.Show("Child1");
}
}
public class Child2 : Parent
{
public new string show2()
{
return "Child1:new" + this.GetType().ToString();
}
public override string show()
{
return "Child2" + this.GetType().ToString();
}
public void message()
{
MessageBox.Show("Child2");
}
}
Running the following
Child1 c1 = new Child1();
Child2 c2 = new Child2();
List<Parent> l = new List<Parent>();
l.Add(c1);
l.Add(c2);
foreach (Parent p in l)
{
p.msgShow2();
//c1 will be derived
//c2 will call the base
}
No comments:
Post a Comment