C#覆盖公共成员,并使其私人 [英] C# override public member and make it private
问题描述
可能吗?你可以改变的任何访问的到的什么的东西?
Possible? Can you change the access of anything to anything else?
推荐答案
没有,你可以的隐藏在子类中的私有方法的公有成员,但你不能替换有私单子类中的公共成员。而且,实际上,它不只是一个公共/私人的事情,这也适用于缩小一般访问。
No, you can hide a public member with a private method in a subclass, but you cannot override a public member with a private one in a subclass. And, in actually, it's not just a public/private thing, this applies to narrowing the access in general.
修订:通过隐藏了更严格的访问 - 在这种情况下,私人的访问 - 你会的还是的看到从基类或子类的基类成员引用,但它会推迟到提供新的访问级别时,新的方法。
Revised: By hiding with a more restrictive access - in this case private access - you will still see the base class member from a base-class or sub-class reference, but it would defer to the new method when available from the new access level.
因此,在一般情况下,当你躲,躲花费precedence时,在其访问级别可见。否则原来的方法是使用所述一个
So in general, when you hide, the hide takes precedence when visible at its access level. Otherwise the original method is the one used.
public class BaseClass
{
public virtual void A() { }
public virtual void B() { }
}
public class SubClass
{
// COMPILER ERROR, can't override to be more restrictive access
private override void A() { }
// LEGAL, you can HIDE the base class method, but which is chosen
// depends on level accessed from
private new void B() { }
}
所以 SubClass.B()
隐藏的仅仅是基类的方法时,它可以访问。也就是说,如果你调用 SubClass.B()
子类的内部
那么它将<$的隐藏表单C $ C> B(),但因为 B()
是私有的,它是不可见的自身之外的类,因此他们仍然看到 BaseClass.B()
。
So SubClass.B()
ONLY hides the base class methods when it is accessible. That is, if you call SubClass.B()
inside of SubClass
then it will take the hidden form of B()
, but since B()
is private, it is not visible to classes outside of itself, and thus they STILL see BaseClass.B()
.
长和短的是:
1)不能覆盖的方法以增加限制(接入明智的)。 2)可以隐藏与更具限制性一种方法,但它只会产生作用,其中该新的接入类型是可见的,否则一个都代表着所述基
1) You cannot override a method to be more restrictive (access wise). 2) You can hide a method with a more restrictive one, but it will only have an effect where that new access type is visible, otherwise the base one stands.
public class BaseClass
{
public virtual void A() { }
public virtual void B() { }
}
public class SubClass : BaseClass
{
public virtual void A() { B(); }
// legal, you can do this and B() is now hidden internally in SubClass,
// but to outside world BaseClass's B() is still the one used.
private new void B() { }
}
// ...
SubClass sc = new SubClass();
BaseClass bc = new BaseClass();
// both of these call BaseClass.B() because we are outside of class and can't
// see the hide SubClass.B().
sc.B();
bc.B();
// this calls SubClass.A(), which WILL call SubClass.B() because the hide
// SubClass.B() is visible within SubClass, and thus the hide hides BaseClass.B()
// for any calls inside of SubClass.
sc.A();
这篇关于C#覆盖公共成员,并使其私人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!