【问题标题】:Extension method not accessible from list of derived type无法从派生类型列表访问扩展方法
【发布时间】:2021-11-19 02:51:49
【问题描述】:

我正在为自己做一个小练习项目,我正在尝试在我的测试中调用这个扩展方法

var days = account.Transactions.PassDays(10, Today);

这给了我这个错误

CS1929    'List<Transaction>' does not contain a definition for 'PassDays' and the best extension method overload 'PassTime.PassDays(List<Event>, int, DateTime)' requires a receiver of type 'List<Event>'

using语句高亮,扩展方法声明为

public static IEnumerable<Day> PassDays(this List<Event> events, int daysToPass, DateTime startTime)

我尝试使用它的 List 是一个派生自 Event 类的类。我读过的所有内容都表明这应该可行。

public record Transaction : Event
public record Event : IEvent

【问题讨论】:

  • List&lt;Transaction&gt; 不是List&lt;Event&gt; (并且不是派生自)所以你期望什么?如果你想使用协方差,那么你需要使用像IEnumerable这样的接口
  • 这是因为Transaction 继承了EventList&lt;Transaction&gt; 没有继承List&lt;Event&gt;?如果不将其作为特定于List&lt;Transaction&gt; 的扩展,您的建议是什么,因为我计划对继承Event 的其他类使用相同的方法。刚看到你的编辑,我会试试的。

标签: c# .net inheritance extension-methods


【解决方案1】:

使用

public static IEnumerable<Day> PassDays(this IEnumerable<IEvent> events, int daysToPass, DateTime startTime)

解决了这个问题。 (IEvent 对此没有必要,但我进行了更改以期望它更有用)也许其他人可以解释为什么这样做。

【讨论】:

猜你喜欢
  • 2017-11-28
  • 2014-06-22
  • 2023-04-09
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多