繁体   English   中英

C# 中的受保护方法 inheritance

[英]Protected method inheritance in C#

在阅读有关受保护的访问修饰符的文档后,我编写了一个简单的 C# 代码,但我收到了很多不合逻辑的错误。 我找不到任何解决方案。

using System;

public class WeaponController
{
    protected void Reload()
    {
        Console.WriteLine("Reload");
    }

    protected virtual void Shoot()
    {

    }
}

public class SMGController : WeaponController
{

    private override void Shoot()
    {
        Console.WriteLine("Shoot");
    }
}

public class Test
{
    public static void Main()
    {
        var test = new SMGController();
        test.Shoot();
        test.Reload();
    }
}

我收到以下错误:

prog.cs(19,27): error CS0621: SMGController.Shoot()': virtual or abstract members cannot be private prog.cs(19,27): error CS0507: SMGController.Shoot()': cannot change access modifiers when覆盖protected' inherited member WeaponController.Shoot()' prog.cs(10,25):(与先前错误相关的符号位置)编译失败:2 个错误,0 个警告

如果我将 SMGController 中的 Shoot() 方法的访问修饰符更改为 protected,我会收到更多错误:

prog.cs(30,8):错误 CS1540:无法WeaponController.Shoot()' via a qualifier of type '。 限定符必须是Test' or derived from it prog.cs(10,25): (Location of the symbol related to previous error) prog.cs(30,8): error CS0122: WeaponController.Shoot()' 是由于其保护级别 prog.cs(10,25) 无法访问:(与先前错误相关的符号位置) prog.cs(31,8):错误 CS1540:无法WeaponController.Reload()' via a qualifier of type SMGController'。 限定符必须是Test' or derived from it prog.cs(5,17): (Location of the symbol related to previous error) prog.cs(31,8): error CS0122: WeaponController.Reload()' 是由于其保护级别 prog.cs(5,17) 无法访问:(与先前错误相关的符号位置)编译失败:4 个错误,0 个警告

我的代码有什么问题?

您不能从 class 外部调用protected的方法,即从Test调用WeaponController.Shoot

此外,如果您覆盖protected的方法,它也必须是protected的。

显然,您希望Reload and Shootpublic ,因此您可以从Test.Main调用它们。

protected修饰符意味着只有class 本身或子类可以访问Shoot

您正在尝试从与SMGControllerWeaponController没有 inheritance 关系的其他 class Test访问它,并且protected的修饰符禁止此类访问。

有关参考,请参阅https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected ,尤其是第一节中的这一行:

受保护的成员可在其 class 内和派生的 class 实例中访问。

您可以通过将Shoot public来解决此问题。 或者,如果您坚持保持它protected ,那么您将需要添加一个方法,例如public PublicShoot() ,然后调用受保护的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM