Can you override private virtual methods?

﹥>﹥吖頭↗ 提交于 2019-12-21 04:12:17

问题


I think you can and my colleage thinks you cannot!


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/2456222/can-you-override-private-virtual-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!