可能吗?您能将任何东西的访问权限更改为其他任何东西吗?
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
中调用SubClass.B()
,它将采用被隐藏的B()
形式,但由于B()
是私有的,它对自身外部的类不可见,因此他们仍然看到BaseClass.B()
。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();
不行。
通常处理这种情况的方式是抛出NotImplementedException
或类似的异常。
您无法缩小或扩大重写成员的可见性。但是,您可以使用new
关键字定义另一个方法,该方法可以为您提供具有相同名称但在多态性方面不兼容的新方法。
public class A : B
{
public new void Foo()
{
base.Foo();
}
}
B
,则即使在 A
中覆盖了该方法,它也将可用。 - Femaref
RightToLeft
这样的一些属性在现有情况下根本没有意义。 - Mark LalorIList<T>
但是没有办法实现Add
或者Remove
方法;socket
是一个stream
,但是你无法在其上执行seek
操作。 - Gabe