下面的代码给我编译器错误:
'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());
}
}
}
答案 0 :(得分:0)
foo()
是Base
的公共接口(及其派生类)的一部分。因此,您无法将其隐藏在Derived
中,因为它会破坏合同。