Can you override private virtual methods?

2019-03-26 17:52发布

I think you can and my colleage thinks you cannot!

标签: c# virtual
3条回答
小情绪 Triste *
2楼-- · 2019-03-26 18:30

You can't even declare private virtual methods. The only time it would make any sense at all would be if you had:

public class Outer
{
    private virtual void Foo() {}

    public class Nested : Outer
    {
        private override void Foo() {}
    }
}

... that's the only scenario in which a type has access to its parent's private members. However, this is still prohibited:

Test.cs(7,31): error CS0621: 'Outer.Nested.Foo()': virtual or abstract members cannot be private
Test.cs(3,26): error CS0621: 'Outer.Foo()': virtual or abstract members cannot be private

查看更多
啃猪蹄的小仙女
3楼-- · 2019-03-26 18:44

Your colleague is right. You can't declare private virtual methods because there's no point (since there'd be no way to override them)...

But you can override protected virtual methods.

查看更多
狗以群分
4楼-- · 2019-03-26 18:51

You won't fund your private method in your derivative class. So the virtual keyword has no sens in this case.

查看更多
登录 后发表回答