C# 中方法隐藏如何工作?
为什么下面的程序会打印
B
B
(应该如此)
public class A
{
public void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void Print()
{
Console.WriteLine("B");
}
public void Print2()
{
Print();
}
}
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Print();
b.Print2();
}
}
,但是如果我们像这样删除 B 类中的关键字“public”:
new void Print()
{
Console.WriteLine("B");
}
它就会开始打印
A
B
?
Why the following program prints
B
B
(as it should)
public class A
{
public void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void Print()
{
Console.WriteLine("B");
}
public void Print2()
{
Print();
}
}
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Print();
b.Print2();
}
}
but if we remove keyword 'public' in class B like so:
new void Print()
{
Console.WriteLine("B");
}
it starts printing
A
B
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您删除
public
访问修饰符时,您就删除了从Main
函数调用 B 的new Print()
方法的任何能力,因为它现在默认为私有
。 Main 无法再访问它。唯一剩下的选择是退回到从 A 继承的方法,因为这是唯一可访问的实现。 如果您要从另一个 B 方法中调用 Print(),您将获得 B 实现,因为 B 的成员将看到私有实现。
When you remove the
public
access modifier, you remove any ability to call B'snew Print()
method from theMain
function because it now defaults toprivate
. It's no longer accessible to Main.The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.
您正在将
Print
方法设置为private
,因此唯一可用的Print
方法是继承的方法。You're making the
Print
methodprivate
, so the only availablePrint
method is the inherited one.在外部,新的 B.Print() 方法不再可见,因此调用 A.Print()。
不过,在该类中,新的 B.Print 方法仍然可见,因此该方法由同一类中的方法调用。
Externally, the new B.Print()-method isn't visible anymore, so A.Print() is called.
Within the class, though, the new B.Print-method is still visible, so that's the one that is called by methods in the same class.
当您从类 b 中删除关键字 public 时,新的 print 方法在类外部不再可用,因此当您从主程序中执行 b.print 时,它实际上调用了 A 中可用的公共方法(因为 b继承 a 并且 a 仍将 Print 作为公共)
when you remove the keyword public from class b, the new print method is no longer available outside the class, and so when you do b.print from your main program, it actually makes a call to the public method available in A (because b inherits a and a still has Print as public)
如果没有 public 关键字,则该方法是私有的,因此不能由 Main() 调用。
但是,Print2() 方法可以调用它,因为它可以看到自己类的其他方法,即使是私有方法。
Without the public keyword then the method is private, therefore cannot be called by Main().
However the Print2() method can call it as it can see other methods of its own class, even if private.