【问题标题】:What does it mean to inherit from a list of a class? (C#) [duplicate]从类列表继承是什么意思? (C#)[重复]
【发布时间】:2020-11-04 07:46:06
【问题描述】:

例如:

public class AssetCollection : List<Asset>

与从类中正常继承相比,如何使用它?我不能像在 List&lt;string&gt; 或 int 等中存储字符串那样正常使用类似的东西,那么如何使用呢?

【问题讨论】:

标签: c#


【解决方案1】:

在这里,您创建了一个新的类类型,它扩展了 List&lt;Asset&gt; 的功能以专门化其行为。

例如你可以添加一个属性来表示总金额:

using System.Linq;

public class AssetCollection : List<Asset>
{
  public int Total
  {
    get
    {
      return Items.Sum(asset => aasset.Amount);
    }
  }
}

这里我们使用 Linq 扩展方法来做列表中每个资产数量的总和。

因此,您可以添加您想要或需要管理资产列表的任何字段、任何属性和任何方法。

但是这里列表的所有公共属性和方法都暴露了。

通常我们希望有一个强大的封装,只提供需要的东西,我们写道:

public class AssetCollection
{
  private readonly List<Asset> Items = new List<Asset>();

  public int Count
  {
    get { return Items.Count; }
  }

  public int Total
  {
    get
    {
      return Items.Sum(asset => aasset.Amount);
    }
  }

  public void Add(Asset asset)
  {
    Items.Add(asset);
  }
}

因此,我们将所有需要的行为包装到列表项中,而忘记了我们想要保护但用于在内部管理列表的内容。

这称为组合,而不是使用继承

https://www.tutorialspoint.com/composition-vs-aggregation-in-chash

https://www.c-sharpcorner.com/article/difference-between-composition-and-aggregation/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 2017-02-17
    • 2019-09-12
    • 2022-01-12
    • 2014-03-23
    • 2017-10-16
    • 2011-01-22
    相关资源
    最近更新 更多