c# - 防止任何子类覆盖/隐藏方法 c#;为父类(super class)保留方法签名

标签 c# oop

<分区>

我的问题属于这种情况

class A
{
    public virtual void show()
    {
         Console.WriteLine("Hey! This is from A;");
    }
}
class B:A
{
    public sealed override void show()
    {
         Console.WriteLine("Hey! This is from B;");
    }
}
class C:B
{
    public new void show()
    {          
         Console.WriteLine("Hey! This is from C;");         
    }          
}

class A
 {
      public  void show()
      {
           Console.WriteLine("Hey! This is from A;");
      }
 }
 class B:A
 {
      public new void show()
      {
               Console.WriteLine("Hey! This is from B;");
      }
 }

在上面的代码中,C 类隐藏了 B 类的方法 Show()

Q. How i can be sure that no Subclass Override as well as Hides method which are already defined in SuperClass

类似这样的东西或者可能像 readonly 用于字段的关键字

 class A1
 {
      public sealed void show() // I know it will give compilation error
      {
           Console.WriteLine("Hey! This is from A1");
      }
 }
 class B1 : A1
 {
      public void show()
      {
           Console.WriteLine("You must get a compilation Error if you create method with this name and parameter");
      }
 }

有没有这样的关键词?

编辑 1:

Yes i want to prevent the extender to be sure that it uses the right implementation with the method name and parameter coz if some one else looks into code it should be right

最佳答案

防止子类隐藏该方法的唯一方法是使类密封,从而防止任何子类。如果可以有任何子类,那么它们可以隐藏该方法,而您对此无能为力。

关于c# - 防止任何子类覆盖/隐藏方法 c#;为父类(super class)保留方法签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18923879/

相关文章:

c# - 使用索引查找字符串中的任何单词

c# - 在 Winform 中托管 RemoteAPP session

python - 如何在Python中创建嵌套的生成器结构?

java - 动态实现接口(interface)?

C# 文件路径通过数据库模拟

c# - 从对象方法中调用管理器/服务类好吗?

c# - 计时器可以安全地废弃吗

c++ - 自定义类中的 move 与复制性能

C#避免装箱和重复代码

c# - 关于DI的问题以及如何解决一些问题