【问题标题】:How do I specify multiple constraints on a generic type in C#?如何在 C# 中对泛型类型指定多个约束?
【发布时间】:2023-03-17 14:58:02
【问题描述】:

对多种类型设置约束的语法是什么?基本示例:

class Animal<SpeciesType> where SpeciesType : Species

我想在以下定义中对这两种类型进行约束,使得SpeciesType 必须从 Species 继承,OrderType 必须从 Order 继承:

class Animal<SpeciesType, OrderType>

【问题讨论】:

    标签: c# .net oop generics type-constraints


    【解决方案1】:
    public class Animal<SpeciesType,OrderType>
        where SpeciesType : Species
        where OrderType : Order
    {
    }
    

    【讨论】:

    • 谢谢!如果我不经常写它,我总是会忘记它!
    【解决方案2】:

    你应该可以走了:

    class Animal<SpeciesType, OrderType>
        where SpeciesType : Species
        where OrderType : Order {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多