是否可以在指定的禁止使用某些类型的泛型类的约束?我不知道这是否是可能的,如果是这样,我不知道什么样的语法会。是这样的:
Is it possible to specify a constraint on a generic class that disallows certain types? I don't know if it is possible and if it is, I am not sure what the syntax would be. Something like:
public class Blah<T> where : !string {
}
我似乎无法找到任何记号,让这样的一个制约因素。
I can't seem to find any notation that would allow such a constraint.
你可以得到的最接近的是一个运行时间限制。
The closest you can get is a run-time constraint.
修改:最初我把运行时检查在构造函数调用。这实际上不是最佳的,因为它会在每一个实例的开销;我相信这将是更明智的把在检查中的静态的构造函数,将一次每个用作 T
参数类型调用你的胡说&LT; T&GT;
键入
Edit: Originally I put the run-time check in the constructor call. That's actually not optimal, as it incurs overhead on every instantiation; I believe it would be much more sensible to put the check in the static constructor, which will be invoked once per type used as the T
parameter for your Blah<T>
type:
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.");
}
}
}
显然并不理想,但如果你把这个约束到位的和的文件的事实,字符串
是不支持的类型参数(例如,通过XML注释),你应该得到的地方的附近的编译时间约束的有效性。
Obviously not ideal, but if you put this constraint in place and document the fact that string
is not a supported type argument (e.g., via XML comments), you should get somewhere near the effectiveness of a compile-time constraint.