为什么C#中的虚函数需要具有相同的访问级别修饰符?

时间:2019-06-06 05:03:50

标签: c#

下面的代码给我编译器错误:

'Rextester.Derived.foo()': cannot change access modifiers when overriding 'public' inherited member 'Rextester.Base.foo()'

为什么不能派生类将重写功能的实现保持为私有? Cpp允许这样做。

我发现一个用例是强制开发人员使用Base类。在使用大型代码库时,我认为这很有用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    class Base
    {
        public virtual string foo()
        {
            return "hi base";
        }
    }

    class Derived : Base
    {
        protected override string foo()
        {
            return "bye derived";
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Base b = new Derived();

            //Your code goes here
            Console.WriteLine(b.foo());
        }
    }
}

代码链接:https://rextester.com/LBQO45364

1 个答案:

答案 0 :(得分:0)

foo()Base的公共接口(及其派生类)的一部分。因此,您无法将其隐藏在Derived中,因为它会破坏合同。