Skip to main content
 首页 » 编程设计

c#之返回更具体的类型是隐藏基类属性的好用例吗

2024年02月06日13Free-Thinker

<分区>

在我目前正在维护的一个项目中,我们有一个核心基类,它具有一种上下文对象的属性:

public abstract class Base 
{ 
  public BaseContext Context { get; protected set; } 
} 

通常如果 Base 被派生,BaseContext 也需要被派生,并且您通常需要在派生类中有更具体的上下文。所以我认为拥有以下内容可能会很不错:

public class Derived : Base 
{ 
  public new DerivedContext Context 
  { 
    get { return (DerivedContext) base.Context; } 
    protected set { base.Context = value; } 
  } 
} 

从类型安全的角度来看,这一切都应该没问题,除了强制转换,但它不应该失败,因为类只能设置属性本身。在我实际上需要派生上下文的属性/方法的少数情况下,使用它可以减少代码中的一些转换,否则我将拥有 ((DerivedContext) Context).Foo。

是否有任何危险信号会反对这种阴影?

(再想一想,可能还有另一种方法,使用泛型来实现相同的目的:

public abstract class Base<TContext> where TContext : BaseContext 
{ 
  public TContext Context { get; protected set; } 
} 
 
public class Derived : Base<DerivedContext> {} 

不需要隐藏基本成员。可能总体上更清洁,也许吧。)