【问题标题】:C# hide method FOR baseclassC#基类隐藏方法
【发布时间】:2021-08-27 17:35:51
【问题描述】:

我想知道这样的事情在 C# 中是否可行:

public class A
{
    public string Foo() { return "Foo"; }
}

public class B : A
{
    public string Bar() { return Foo(); }
}

public class C : B
{
    public new string B.Foo() { return "Bar"; } // Hide A.Foo in B
}

Main()
{
    C c = new C();
    Console.WriteLine(c.Bar()); // Want to get "Bar"
}

public new string B.Foo() { return "Bar"; } 我的意思是在 C 中做一些事情(不改变 A 或 B),其结果与在 B 中实现 public new string Foo() { return "Bar"; } 的结果相同。因此,隐藏一个基类的方法继承层次结构。

【问题讨论】:

  • 是的,virtual
  • @gunr2171 只更改 C 而不是隐藏 Bar
  • 你的手在背后绑得很紧。
  • 我想在 B 中隐藏 Foo(),只链接 C
  • 答案基本上是“不”。我建议你引入一个新的虚拟方法并覆盖它 - 基本上,按照预期的方式使用继承。

标签: c#


【解决方案1】:

您想要的是virtual,它允许您覆盖继承类型中的基本行为。

public class A
{
    public virtual string Foo() { return "Foo"; }
}

public class B : A
{
    public virtual string Bar() { return Foo(); }
}

public class C : B
{
    public override string Foo() { return "Bar"; } // Hide A.Foo in B
}

这会输出“bar”

【讨论】:

  • 不,不改变 A 或 B。这就是为什么我要询问方法隐藏,而不是覆盖
  • 你可以在不改变 A 或 B 的情况下做到这一点只有当它们被设计为使 Foo 在子类中“可覆盖”。这是通过声明方法virtual 来完成的。基类必须选择在 C# 中覆盖。
  • @DavidBrowne-Microsoft 我不想覆盖,我想隐藏
  • 隐藏仅适用于隐藏类型的实例。 B b = new C(); b.Foo(); 将运行 B 的 Foo 如果 C 只隐藏它。所以你不想隐藏。你所描述的是压倒一切,而不是隐藏。
  • 这是不合理的,因为你刚刚给出的确切原因。反射使用运行时 api,编译器不保证,这是当前限制你的。此外,不安全的代码就是不安全的。如果您想在安全的、编译时驱动的检查参数中执行此操作,那么根据编译器 根本不可能,而 virtual+override 为您提供了一种类型安全的方式来表达行为。否则,您必须包装实例。
猜你喜欢
  • 2011-04-18
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 2012-06-07
  • 2015-03-08
  • 2011-09-14
相关资源
最近更新 更多