如何指定.NET Generics约束中不允许的类型?

Les*_*nks 12 .net c# generics constraints

是否可以在不允许某些类型的泛型类上指定约束?我不知道是否可能,如果是,我不确定语法是什么.就像是:

public class Blah<T> where : !string {
}
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到任何允许这种约束的符号.

Dan*_*Tao 11

您可以获得的最接近的是运行时约束.

编辑:最初我把运行时检查放在构造函数调用中.这实际上并不是最优的,因为它会在每次实例化时产生开销; 我相信将检查放在静态构造函数中会更加明智,每个类型用作类型的T参数时将调用一次Blah<T>:

public class Blah<T> {
    static Blah() {
        // This code will only run ONCE per T, rather than every time
        // you call new Blah<T>() even for valid non-string type Ts
        if (typeof(T) == typeof(string)) {
            throw new NotSupportedException("The 'string' type argument is not supported.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

显然不理想,但如果你把这个约束放在适当的位置记录string不是受支持的类型参数的事实(例如,通过XML注释),你应该得到一个接近编译时约束的有效性.