如何指定 .NET 泛型约束中不允许的类型?
是否可以在泛型类上指定不允许某些类型的约束?我不知道这是否可能,如果可能,我不确定语法是什么。就像:
public class Blah<T> where : !string {
}
我似乎找不到任何允许这种约束的符号。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以获得的最接近的是运行时约束。
编辑:最初我将运行时检查放在构造函数调用中。这实际上不是最佳的,因为它会在每次实例化时产生开销;我相信将检查放在 static 构造函数中会更明智,该构造函数将针对用作
Blah< 的
类型:T
参数的每个类型调用一次。 T>显然不理想,但是如果您将此约束放在适当的位置并记录
string
不是受支持的类型参数的事实(例如,通过XML 注释),你应该有所收获接近编译时约束的有效性。The closest you can get is a run-time constraint.
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 yourBlah<T>
type: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.不,您不能直接指定“否定”类型约束。
No, you can't directly specify "negated" type constraints.
约束只能是正约束,如文档中所述。
您唯一能做的就是指定哪些类型可以放入泛型类型中,但不能指定哪些类型不能放入其中。
Constraints can only be positive constraints, as outlined in the documentation.
The only thing you can do is specify what types can be put into the generic type, but you cannot specify what can't be put into them.
以下是允许的约束(更多详细信息),
Here are the allowed constraints (more detail)