【问题标题】:C# Inheriting from a SortedList [closed]C# 从 SortedList 继承 [关闭]
【发布时间】:2020-09-09 11:21:18
【问题描述】:

我想问一下如何正确地从排序列表中继承一个类:

public class Plates : SortedList<string,Plate> {
}

上面的代码没有给我错误,我很困惑,因为为了继承 Enumerable 我需要添加额外的方法来枚举元素。

谁能告诉我如何正确添加排序列表的索引和添加方法?

我是否应该编写类似于下面的代码来将 Plate 对象存储在此类中。除了 IEnumerable 之外,我真的没有太多继承其他类的经验。

public class Plates : SortedList<string,Plate> {
    SortedList<string,Plate> plateList = new  SortedList<string,Plate>();
}

【问题讨论】:

  • 我认为更大的问题是:为什么要“从排序列表中继承一个类”?
  • IEnumerable 是一个接口,SortedList 是一个类。这就是为什么在第二种情况下您不需要额外的方法。
  • IEnumerable 是一个接口。它不是继承的,而是实施的。尽管有许多扩展方法在IEnumerable“免费”上运行,但它没有自己的默认实现。
  • 那么to add additional methods to enumerate elements 有什么问题? - 你可以枚举this 例如:dotnetfiddle.net/Tz4LFI
  • because for inheriting Enumerable 你能给我们指出这个Enumerable 类,以便我们看看它的作用吗?

标签: c# sortedlist


【解决方案1】:

如果您想覆盖和处理排序列表上的操作,我建议使用组合而不是继承:

public class Plates: : IEnumerable<System.Collections.Generic.KeyValuePair<string, Plate>> {
    private SortedList<string,Plate> st;
}

这将迫使您实现IEnumerable 方法并使用您想要的SortedList 功能区分实现。

如前所述,类(如果它们不是abstract)不会强迫你实现任何东西,如果你继承它们。

【讨论】:

  • 您的意思是IEnumerable&lt;KeyValuePair&lt;string, Plate&gt;&gt; 还是只是IEnumerable&lt;Plate&gt;
  • 可以看看我上面的代码吗?我担心它是否正确以及元素是否会被排序?
  • 两者都是。它将被排序。我认为您甚至不需要实现IEnumerable,只需直接使用SortedList即可。
猜你喜欢
  • 2016-12-12
  • 1970-01-01
  • 2017-08-20
  • 2017-01-12
  • 2011-11-19
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 2016-07-10
相关资源
最近更新 更多