C#隐藏成员
当子类继承父类的时候,在子类中定义一个与父类完全相同的成员,会造成隐藏。
一般这种情况,是偶然的。
即,你写了A类,但过了段时间写了B类继承A类,
但是忘记了A类里面有一个public int Counter成员,
在B里面又定义了一遍,
这种情况,不会报错,但会提示你成员被隐藏。
结果就是,你引用哪个类,你就会调用哪个类的Counter成员。
实例:
namespace 隐藏成员
{
class A
{
public int Counter = 1;}
class B:A
{
public int Counter = 2;
}
class Program
{
static void Main(string[] args)
{
A a = new A();
Console.WriteLine(a.Counter); // 1
B b = new B();
Console.WriteLine(b.Counter); // 2
A a2 = new B();
Console.WriteLine(a2.Counter); // 1Console.ReadKey();
}
}
}
输出:
1
2
1
按照如下规则进行解析:
✦ 编译时对A的引用会绑定到A.Counter
✦ 编译时对B的引用会绑定到B.Counter
new关键字
你可以:
class B:A
{
public new int Counter = 2;
}
ta的作用仅仅是消除警告。
NewVsOverride
namespace NewVsOverride
{
public class BasicClass
{
public virtual void myfunction() => Console.WriteLine("1");
}public class OverRider : BasicClass
{
public override void myfunction()=> Console.WriteLine("2");
}public class Hider : BasicClass
{
public new void myfunction()=> Console.WriteLine("3");
}
class Program
{
static void Main(string[] args)
{
OverRider rider = new OverRider();
Hider hider = new Hider();
BasicClass a = rider;
BasicClass b = hider;
rider.myfunction(); // 2 --指向自己
hider.myfunction(); // 3 --指向自己
a.myfunction(); //2 --指向自己
b.myfunction(); //1 --指向父类 --这就是new关键字的作用
Console.Read();
}
}
}
输出:
2
3
2
1
new关键字让方法互相独立了,所以存在2个方法。
override关键字重写了父类的方法,所以只存在1个方法。
Today's comments have reached the limit. If you want to comment, please wait until tomorrow (UTC-Time).
There is 04h33m19s left until you can comment.