泛型 - 其中T是多少? [英] Generics - where T is a number?
问题描述
我试图找出一种方法来创建只有数字类型的通用类,做一些计算。
I'm trying to figure a way to create a generic class for number types only, for doing some calculations.
有所有数字类型(int,双,浮法...)我失踪???
Is there a common interface for all number types (int, double, float...) that I'm missing???
如果没有,会是怎样创造这样一个类的最佳方式?
If not, what will be the best way to create such a class?
更新:
最主要的我想实现的是检查谁是T类型的两个变量之间的大。
The main thing I'm trying to achieve is checking who is the bigger between two variables of type T.
推荐答案
什么版本的.NET您使用的是?如果您使用的是.NET 3.5,那么我有一个通用的运营商实施在<一个HREF =http://www.yoda.arachsys.com/csharp/miscutil/> MiscUtil (免费等)。
What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).
这有一个像方法,不要再增加&LT; T&GT;(T X,T Y)
,并为不同类型的运算(如 DateTime的其他变种+时间跨度
)。
This has methods like T Add<T>(T x, T y)
, and other variants for arithmetic on different types (like DateTime + TimeSpan
).
此外,这适用于所有的内置,解除和定制的运营商,以及缓存委托的表现。
Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.
这是为什么这是棘手的一些额外的背景是这里。
Some additional background on why this is tricky is here.
您可能也想知道,解决了这个问题排序的动态
(4.0)间接太 - 即
You may also want to know that dynamic
(4.0) sort-of solves this issue indirectly too - i.e.
dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect
重约注释&LT;
/ &GT;
- 你不实际的需求此操作;你只需要:
Re the comment about <
/ >
- you don't actually need operators for this; you just need:
T x = ..., T y = ...
int c = Comparer<T>.Default.Compare(x,y);
if(c < 0) {
// x < y
} else if (c > 0) {
// x > y
}
这篇关于泛型 - 其中T是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!