Prevent calling base class implemented interface method in the derived class C#

大兔子大兔子 提交于 2019-12-06 10:32:53

No, this isn't possible - it would break the whole point of polymorphism. In particular, imagine you didn't use var, but used the types explicitly:

Sub1 s2 = new Sub2();
s2.Test();

That has to compile:

  • The first line has to compile because Sub2 is derived from Sub1.
  • The second line has to compile because you wanted s1.Test() to compile, where the compile-time type of s1 is Sub1 as well.

As a rule of thumb, if you have two classes X and Y, and only some of the public operations on X are valid for Y, then Y shouldn't derive from X. You should be able to treat any instance of a derived class as if it's an instance of the base class (and all interfaces it implements).

You want the Test method to be available only in Sub1 but still share the same properties with Sub2. This can be achieved by changing the inheritance chain from this:


to this:

Use sealed protected override bool Test() in Sub1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!