【发布时间】:2012-02-07 23:13:29
【问题描述】:
我已经实现了一个单例类,并不断收到警告说我正在编写的方法是“在密封类中声明的新受保护成员”。它不会影响构建,但我真的不想忽略警告,以防它在以后引起问题?我知道密封类是一个不能被继承的类 - 所以它的方法不能被覆盖,但我仍然不明白为什么下面的代码会给我警告(是因为使用了单例设计吗?):
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() 方法有关。 编辑:将 public void MethodName() 更改为 protected void MethodName()
【问题讨论】:
-
如果您将
Nested类设为private,会发生什么? -
我没有看到任何受保护的东西......
-
什么也没发生,警告仍然存在。老实说,我认为它与单例设计没有任何关系 - 它更多地与密封类与访问修饰符有关,但我想我会提到它并包含嵌套类代码以防万一。
-
我遗漏了一些东西,您的示例代码没有收到任何警告。
-
我也是,您的所有工件都是私有的、公共的和来自您的源的内部的。您粘贴的代码是否与给您警告的代码相同?您是否保护了构造函数?