C#覆盖公共成员并将其设为私有

Mar*_*lor 12 .net c# overriding private public

可能?你可以改变访问什么什么别的吗?

Jam*_*are 15

不可以,您可以在子类中使用私有方法隐藏公共成员,但不能使用子类中的私有成员覆盖公共成员.而且,实际上,它不仅仅是公共/私人事物,这适用于缩小访问范围.

修订:通过用更多限制访问隐藏-在这种情况下,私人的访问-你将仍然看到从基类或子类的引用基类成员,但它会推迟到可用时从新访问级别的新方法.

因此,通常,当您隐藏时,隐藏在其访问级别可见时优先.否则原始方法是使用的方法.

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() { }
}
Run Code Online (Sandbox Code Playgroud)

因此,SubClass.B()只有在可访问的基类方法时才会隐藏它们.也就是说,如果你SubClass.B()在里面调用SubClass它将采用隐藏的形式B(),但由于B()它是私有的,它本身以外的类是不可见的,因此它们仍然可以看到BaseClass.B().

它的长短是:

1)您不能覆盖方法以限制更多(访问明智).2)您可以隐藏具有更严格限制的方法,但它只会在新的访问类型可见的情况下产生效果,否则基本的显示效果.

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();
Run Code Online (Sandbox Code Playgroud)