【问题标题】:Multiple where for generic type泛型类型的多个 where
【发布时间】:2020-06-10 02:09:21
【问题描述】:

我需要为我的类指定一个泛型类型实现一个接口,同时也是一个引用类型。我尝试了下面的代码 sn-ps 但都不起作用

public abstract class MyClass<TMyType> 
   where TMyType : IMyInterface
   where TMyType : class

public abstract class MyClass<TMyType> 
       where TMyType : class, IMyInterface

我无法为一个类型指定多个 where 子句,可以这样做吗?

【问题讨论】:

    标签: c# .net generics


    【解决方案1】:

    关于如何在此处定义多个where 子句的问题链接为重复项。如果该问题确实是重复的,则此“完整”答案必须包含两种情况。

    案例 1 -- 单个泛型有多个约束

    public interface IFoo {}
    
    public abstract class MyClass<T>
        where T : class, IFoo
    {
    }
    

    案例 2 -- 多个泛型,每个都有自己的约束

    public interface IFoo1 {}
    public interface IFoo2 {}
    
    public abstract class MyClass<T1, T2>
        where T1 : class, IFoo1
        where T2 : IFoo2
    {
    }
    

    【讨论】:

      【解决方案2】:

      后一种语法应该没问题(并且可以为我编译)。第一个不起作用,因为您试图在 same 类型参数上提供两个约束,而不是在不同类型参数上。

      请给出一个简短但完整的示例,说明后一种语法不适合您。这对我有用:

      public interface IFoo {}
      
      public abstract class MyClass<T>
          where T : class, IFoo
      {
      }
      

      【讨论】:

      • 好的,谢谢。你是对的,第二个 sn-p 确实有效。抱歉 - 我在尝试时遇到的编译错误与此无关。应该正确阅读!
      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 2015-12-28
      • 2020-04-03
      • 2023-03-24
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多