内部成员可以被覆盖吗?

Did*_*xis 2 .net c# oop

假设您有以下类声明:

public abstract class Foo
{
    public class Bar
    {
        public virtual void DoSomething() { ... }
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以覆盖Foo的子类中的Bar.DoSomething(),la:

public class Quz : Foo
{
    public override void Bar::DoSomething() { ... }
}
Run Code Online (Sandbox Code Playgroud)

显然语法不起作用,但是这样可能吗?

m-y*_*m-y 6

不,但你仍然可以从Foo.Bar类本身继承:

public class BarDerived : Foo.Bar
{
    public override void DoSomething() { ... }
}
Run Code Online (Sandbox Code Playgroud)

我觉得我应该解释说,这样做并不意味着一个派生的类Foo会突然产生一个内部类,BarDerived而只是意味着有一个类可以从中派生出来.有一些方法可以替换您想要用作内部类的类,例如:

public class Foo<T>
    where T : Foo.Bar
{
    private T _bar = new T();

    public class Bar
    {
        public virtual void DoSomething() { ... }
    }
}

public class BarDerived : Foo.Bar
{
    public override void DoSomething() { ... }
}

public class Quz : Foo<BarDerived> { ... }
Run Code Online (Sandbox Code Playgroud)

  • @Didaxis您不知道在使用虚拟成员扩展类时可以覆盖虚拟成员? (2认同)