约束泛型类型参数的数值类型 [英] Constraining a generic type argument to numeric types
问题描述
我定义泛型类型:
public class Point<T> where T : IConvertible, IComparable
我真的很想做的是限制T可是数字类型(整数的花车或之一)有一个在CLR没有INumeric。是否有可能被用在这里来约束型盒装数字类之一的接口的接口或收藏?
What I would really like to do is constrain T to be a numeric type (one of the ints or floats.) There's no INumeric in the CLR. Is there an interface or collection of interfaces that could be used here to constrain the type to one of the boxed numeric classes?
推荐答案
很不幸的是,不行。这是一个的很长一段时间。
Unfortunately, no. This has been a highly requested feature for a long time.
现在强烈要求的功能,最好的选择是可能使用:
Right now, the best option is likely to use:
where T : struct, IConvertible, IComparable<T>
(该结构约束防止串用法...)
(The struct constraint prevents string usage...)
然而,这仍然允许实现要使用的适当的约束的任何用户定义的类型的值。
However, this still allows any user defined value type that implements the appropriate constraints to be used.
这篇关于约束泛型类型参数的数值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!