泛型类型的多个位置

Cha*_*lie 4 .net c# generics

我需要指定我的类的泛型类型实现接口,并且也是引用类型.我尝试了下面的代码片段,但都没有工作

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

public abstract class MyClass<TMyType> 
       where TMyType : class, IMyInterface
Run Code Online (Sandbox Code Playgroud)

我无法为类型指定多个where子句,是否可以执行此操作?

Jon*_*eet 7

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

请提供一个简短但完整的后一种语法示例,不适合您.这对我有用:

public interface IFoo {}

public abstract class MyClass<T>
    where T : class, IFoo
{
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*des 5

关于如何定义多个where子句的问题在此处链接为重复.如果这个问题确实是重复的,那么完整答案必须包含两个案例.

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

public interface IFoo {}

public abstract class MyClass<T>
    where T : class, IFoo
{
}
Run Code Online (Sandbox Code Playgroud)

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

public interface IFoo1 {}
public interface IFoo2 {}

public abstract class MyClass<T1, T2>
    where T1 : class, IFoo1
    where T2 : IFoo2
{
}
Run Code Online (Sandbox Code Playgroud)