【问题标题】:C# - Specifying type parameters of super-class in sub-classes?C# - 在子类中指定超类的类型参数?
【发布时间】:2020-04-16 00:31:06
【问题描述】:

我正在尝试在 C# 中执行以下操作。

public class Parent<T> where T : Parent<???>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

我该怎么做?

【问题讨论】:

  • 你只需要class Parent&lt;T&gt; where T : Parent&lt;T&gt;吗?
  • 在你尝试使用的时候,Parent的定义是不是不完整?
  • @Enigmativity 这是递归的,它不起作用。
  • @PrateekShrivastava 你建议如何重构代码?有什么解决方法吗?
  • @geeko - 不,它工作正常。它会编译并允许您按照您要求的方式定义class Child : Parent&lt;Child&gt;

标签: c# generics inheritance type-parameter


【解决方案1】:

这很好用:

public class Parent<T> where T : Parent<T>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

请注意这一点,因为 c# 不会强制执行真正的 Parent/Child 关系。例如,给定上面的代码,我也可以这样做:

public class Stranger : Parent<Child>
{
}

如果您编写单元测试,那么值得编写一个类型检查器来查找这种错误模式。

【讨论】:

  • 非常有趣——我已经使用这种模式很长时间了,我从没想过它会被这样滥用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
  • 2016-04-04
  • 2023-03-04
  • 2017-04-27
  • 2020-12-16
  • 2021-01-22
  • 2022-09-30
相关资源
最近更新 更多