【问题标题】:How to share C# property code between multiple subclasses of a class, but not all?如何在一个类的多个子类之间共享 C# 属性代码,但不是全部?
【发布时间】:2017-10-31 06:39:12
【问题描述】:

更新 当被问及为什么 A 不直接从 D 继承时,我可能应该说,还有其他类也从 A 继承。假设所有这些子类都有一些来自 A 的共享功能。

我有一个有趣的情况,我认为需要一些组合方法。然而,我目前拥有的是一些继承,导致基类成为神类。

  public abstract class A
  {
      protected SameProperty {get; set;}
      protected SharedMethod();
  }

    public class B : A
    {
         //Uses SameProperty with some of its own variables
        //SharedMethod used.
    }

    public class C : A
    {
         //Also uses SameProperty with some of ITS own variables
         //SharedMethod used.
    }

    public class D : A
    {
        //Does not use SameProperty. Will never use it and there will be many other classes just like this.
        //SharedMethod used.
    }

    public class E : A
    {
        //Does not use SameProperty either.
        //SharedMethod used.
    }

在上面的示例中,B 和 C 使用此属性的 getter 和 setter 代码,否则这些代码会在子类本身中重复。所以我使用 A 在它们之间共享代码。但是 D 和所有其他从 A 继承而永远不需要该属性的对象呢?

我尝试使用 SameProperty 创建一个接口并将其添加到类 B 和 C。这让我想知道这有什么帮助,因为我最终仍将实现属性代码两次。

我也尝试过创建一个静态类,将属性共享为静态类,但这不允许我将 B 类和 C 类所需的变量传递到静态代码中。

我认为我不能使用方法来代替属性(这是什么,Java?)。那么我该如何只使用属性呢?

谢谢, 查基。

更新 2 我添加了问题属性的具体实现,它在某些子类中是必需的,但不是全部。对于那些好奇的人,这是 Xamarin-iOS ViewController 中的代码。

我了解一些用户对 A 的中间子类的建议,该子类 B 和 C 都继承自(比如说,F?)。

但是,假设从 A 继承的子类 D 和 E 有它们自己的中间类 G。但是还需要来自 F 的 SameProperty。我将如何使用所有这些继承级别来做到这一点?当然将 SameProperty 组合到其他类是唯一的方法吗?但是怎么做呢?

bool _bannerDisabled;
public bool BannerDisabled
{
    get
    {
        return _bannerDisabled;
    }
    set
    {
        if (BaseDisabledBanner != null && BaseDisabledBannerHeightConstraint != null)
        {
            _bannerDisabled = value;
            BaseDisabledBannerHeightConstraint.Constant = _bannerDisabled ? _viewHeight : 0;
            BaseDisabledBanner.Hidden = !_bannerDisabled;
            View.LayoutIfNeeded();
        }
    }
} 

【问题讨论】:

  • 在不知道这段代码实际上想要做什么的情况下,我们无法评论架构是否合适或有什么更好的选择。
  • 为什么 D 不是你的基类并让 A 继承它?
  • D 没有业务自称A 的子类,如果它有一个问题 继承A 的任何东西。
  • Ed 搞定了,设计问题,重新考虑。
  • 如果您的类需要使用 A 中的东西而不是覆盖,那么如果您的设计使用组合而不是继承可能更有意义,但仅根据给出的示例的模糊性很难判断。

标签: c# oop inheritance properties composition


【解决方案1】:

也许这些方法可以解决问题:

public abstract class A0
{
    //has common code that should be implemented by all
}
public abstract class B0 : A0
{
    protected SameProperty {get; set;}
}
public class B : B0
{
     //Uses SameProperty with some of its own variables
}
public class C : B0
{
     //Also uses SameProperty with some of ITS own variables
}
public class D : A0
{
    //Does not use SameProperty. Will never use it and there will be many other classes just like this.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    • 2011-02-09
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多