多凡泛型类型类型、多凡泛型

2023-09-03 04:23:03 作者:软甜

我需要指定一个泛型类型,我的类实现一个接口,并且还引用类型。我想无论是code以下的片段,但没有工作

I need to specify that a generic type for my class implements an interface, and is also a reference type. I tried both the code snippets below but neither work

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

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

我不能指定多个,其中一类条款,是有可能做到这一点?

I'm unable to specify multiple where clauses for a type, is it possible to do this?

推荐答案

后者语法应罚款(和编译对我来说)。先不工作,因为你想提供两个约束上的一样的类型参数,而不是在不同类型的参数。

The latter syntax should be fine (and compiles for me). The first doesn't work because you're trying to provide two constraints on the same type parameter, not on different type parameters.

请给后者的语法不是为你工作的一个简短但完整的例子。这对我的作品:

Please give a short but complete example of the latter syntax not working for you. This works for me:

public interface IFoo {}

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