代码之家  ›  专栏  ›  技术社区  ›  Charlie Gevious

通用类型的多个Where

  •  4
  • Charlie Gevious  · 技术社区  · 16 年前

    我需要指定我的类的一个泛型类型实现一个接口,并且也是一个引用类型。我尝试了下面的两个代码片段,但都不起作用

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

    我不能为一个类型指定多个WHERE子句,可以这样做吗?

    2 回复  |  直到 16 年前
        1
  •  7
  •   Jon Skeet    16 年前

    后一种语法应该很好(并为我编译)。第一个不起作用,因为您试图在 相同的 类型参数,不在不同的类型参数上。

    请给出后一种语法不适用的简短但完整的示例。这对我很有用:

    public interface IFoo {}
    
    public abstract class MyClass<T>
        where T : class, IFoo
    {
    }
    
        2
  •  5
  •   Joshcodes    12 年前

    关于如何将多个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
    {
    }