【问题标题】:Generic type where T is derived from a generic type泛型类型,其中 T 派生自泛型类型
【发布时间】:2021-12-30 07:10:20
【问题描述】:

我有一个名为 Foo 的抽象类,它是通用的。
还有一个名为Bar 的类,它也是通用的,但需要从Foo 派生T。但如果不为Foo 指定泛型类型,我就无法做到这一点,我不想这样做 - 我希望从Foo 派生的任何类都符合条件。

abstract class Foo<T> { }

class Bar<T> where T : Foo { }
// This gives me CS0305 - Using the generic type Foo<T> requires 1 type argument.

我确定我缺少某种超级明显的解决方案。

【问题讨论】:

  • 这是你要找的东西:class Bar&lt;T&gt; : Foo&lt;T&gt; { } ?
  • @Karoshee 不。我不希望 Bar 派生自 Foo
  • @CaiusJard 哦,对不起,我明白你的意思。 Question 应该是 Foo

标签: c#


【解决方案1】:

看这里:https://docs.microsoft.com/pl-pl/dotnet/csharp/language-reference/keywords/where-generic-type-constraint

你有两个选择:

  • 创建非泛型类Foo 并让Foo&lt;T&gt; 实现它(就像IEnumerable&lt;T&gt; 实现IEnumerable

  • Bar 使用两个泛型而不是一个

    class Bar&lt;T1,T2&gt; where T1: Foo&lt;T2&gt;

【讨论】:

    【解决方案2】:

    假设QuestionFoo&lt;&gt;,您可以使用:

    class Bar<T, T2> where T : Foo<T2> { }
    

    【讨论】:

    • 哦,是的,很抱歉。
    • 但这不是我想要的。我希望 Bar 采用从 Foo 派生的 any 类,无论它具有什么泛型类型。
    【解决方案3】:

    您可以通过创建一个非通用类来做到这一点,如下所示

    public abstract class Foo { }
    public abstract class Foo<T> : Foo { }
    

    现在您可以将约束与 Foo 一起使用

    public class Bar<T> where T : Foo { }
    

    这将要求TFoo 的一种类型,并且只要您从非通用Foo 派生通用Foo&lt;&gt;,您的T 就必须是Foo&lt;T&gt;

    使用示例:

    public abstract class Foo { }
    public abstract class Foo<T> : Foo { }
    public abstract class Boo : Foo<string> { }
    
    public class Bar<T> where T : Foo { }
    
    public class BarTest : Bar<Boo> { }
    

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 2010-10-22
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 2012-09-08
      • 2011-05-24
      • 2017-01-21
      • 1970-01-01
      相关资源
      最近更新 更多