通用类型约束只接受数字?
在 c# 中:
想象一下我们的情况具有优于泛型类型的功能,其中从概念上讲,我们的泛型类型仅限于数字。
通过说“数字”,我们的目标是能够对 T 类型的变量使用乘法、加法、减法等运算符。
不幸的是,c# 中不接受这样的操作:
public class Image<T> where T : number
请注意,性能也很重要,因此我们不想重新定义数字类型的结构并使用它们。
您认为做到这一点的最佳方法是什么?或者是否有任何设计模式允许我们对泛型类型的变量拥有“高性能”算术函数?
Possible Duplicates:
C# generic constraint for only integers
Generics - where T is a number?
In c#:
Imagine a case that we have a functionality over a generic type in which conceptually our generic type is limited only to numbers.
By saying "number" we aim to be able to use multiply, plus, minus, etc. operators on variables of type T.
Unfortunately something like this is not accepted in c#:
public class Image<T> where T : number
Note that performance is also important so we don't want to go for redefining a struct for numeric types and using them.
What do you think is the best way to do this? Or is there any design patter that allows us to have "high performance" arithmetic functions over variables of a generic type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以失去可读性为代价,您可以重写所有方法,从
到
using
with 任何数字类型的实现。
At the great cost of losing readability, you can rewrite all methods from
to
using
with implementations for any number type.
不幸的是没有这样的限制。存在的最接近的东西是 struct 约束
您还可以在 .net 上搜索 google 数学库,它公开了自己的类型,这些类型具有一个基类,这使得可以将其用作您想要的约束。
Unfortunately there is no such constraint. The closest thing exist is
struct
constraintAlso you can google math libraries for .net which expose there own types which have one baseclass which makes it possible to use it as a constrain you want.