c# - 隐藏在 c# 中的方法以及一个有效的例子。为什么在框架中实现?什么是现实世界的优势?

标签 c# .net oop inheritance polymorphism

谁能用一个有效的例子来解释 C# 中方法隐藏 的实际用法?

如果方法是在派生类中使用new 关键字定义的,那么它不能被覆盖。然后它与创建一个具有不同名称的新方法(除了基类中提到的方法)一样。

是否有使用 new 关键字的特定原因?

最佳答案

我有时对 new 关键字的一个用途是在平行继承树中用于“穷人属性协方差”。考虑这个例子:

public interface IDependency
{
}

public interface ConcreteDependency1 : IDependency
{
}

public class Base
{
  protected Base(IDependency dependency)
  {
    MyDependency = dependency;
  }

  protected IDependency MyDependency {get; private set;}
}

public class Derived1 : Base // Derived1 depends on ConcreteDependency1
{
  public Derived1(ConcreteDependency1 dependency)  : base(dependency) {}

  // the new keyword allows to define a property in the derived class
  // that casts the base type to the correct concrete type
  private new ConcreteDependency1 MyDependency {get {return (ConcreteDependency1)base.MyDependency;}}
}

继承树 Derived1 : Base 对 ConcreteDependency1 : IDependency 有一个“平行依赖”。在派生类中,我知道 MyDependency 是 ConcreteDependency1 类型,因此我可以使用 new 关键字从基类隐藏属性 getter 。

编辑:另见 this blog post by Eric Lippert以获得对新关键字的良好解释。

关于c# - 隐藏在 c# 中的方法以及一个有效的例子。为什么在框架中实现?什么是现实世界的优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1193848/

相关文章:

c# - 尝试下载 osu! 时如何修复 "The SSL connection could not be established, see inner exception."化身

c# - Office.Interop.Word - 如何双面打印文档?

.net - Windows 窗体 : User controls and events

php - 将超全局变量包装在一个类中?

java - java.util 中的模块(集合)

c# - .NET Core 不支持 BeginInvoke? (PlatformNotSupported 异常)

c# - C++/CLI 将现有应用程序转换为托管代码

.net - 无法通过 Exchange 发送电子邮件 : An existing connection was forcibly closed by the remote host

c# - 使用 .NET 4.0 任务并行库强制执行任务顺序

c# - C# 缺乏多重继承是如何导致需要接口(interface)的?