“密封班级受保护成员"警告(单身人士班) [英] 'Protected member in sealed class' warning (a singleton class)

查看:87
本文介绍了“密封班级受保护成员"警告(单身人士班)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一个单例类,并不断收到警告,指出我正在编写的方法是在密封类中声明的新受保护成员".它不会影响构建,但是我真的不想忽略警告,以防以后引起问题吗?我知道密封类是不能继承的类-因此不能重写其方法,但是我仍然不明白为什么以下代码会给我警告(是由于使用了单例设计吗?):

I've implemented a singleton class and keep getting the warning that a method I'm writing is a 'new protected member declared in a seal class.' It's not affecting the build but I don't really want to ignore the warning in case it causes problems later on? I understand a sealed class is a class that cannot be inherited - so it's methods cannot be overridden, but I still don't get why the following code would give me the warning (is it due to the use of the singleton design?):

namespace WPFSurfaceApp
{
public sealed class PresentationManager
{
    PresentationManager()
    {
    }

    protected void MethodName()
    {
    }

    public static PresentationManager Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly PresentationManager instance = new PresentationManager();
    }
}

警告与MethodName()方法有关. 将公共void MethodName()更改为受保护的void MethodName()

The warning is regarding MethodName() method. Change public void MethodName() to protected void MethodName()

推荐答案

警告是因为protected在无法继承的类中没有意义.对于sealed类,它在逻辑上将与private完全相同.

The warning is because protected does not make sense in a class that can't be inherited from. It will logically be exactly the same as private for a sealed class.

本质上这不是一个错误,但是编译器试图吸引您注意以下事实:将其设置为protected而不是private不会给您带来任何好处,并且可能未按照您的预期进行(如果您希望它对子类可见(在密封类中不存在).

It's not an error, per se, but the compiler is trying to draw your attention to the fact that making it protected instead of private will provide you no benefit and may not be doing what you intended (if you intended it to be visible to a sub-class, which can't exist in a sealed class).

是的,您可以放心地忽略它,但是在sealed类中包含protected成员在逻辑上是不一致的.

So, yes, you can safely ignore it, but it's logically inconsistent to have protected members in a sealed class.

编译器警告CS0628

这篇关于“密封班级受保护成员"警告(单身人士班)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆