防止继承?

man*_*654 0 c# c#-3.0 c#-4.0

如何在不使用密封关键字的情况下阻止继承类?

提前致谢.

Ste*_*ner 10

在你的类的构造函数中:

public MyUnsealedClass()
{
  if (this.GetType() != typeof(MyUnsealedClass))
      throw new Exception("Don't do that");
}
Run Code Online (Sandbox Code Playgroud)

为什么不使用sealed关键字呢?

  • 如此多的赞成在ctor中抛出一个例外......我一定是在遗漏一些东西 (3认同)

Mat*_*ord 9

另一种方法是你可以创建一个静态方法,返回你的类型的对象,然后使构造函数私有.这样做的好处是它将创建编译时错误而不是运行时错误.