泛型 - 其中 T 是一个数字? [英] Generics - where T is a number?

查看:28
本文介绍了泛型 - 其中 T 是一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在想办法为数字类型创建一个泛型类,以进行一些计算.

I'm trying to figure a way to create a generic class for number types only, for doing some calculations.

是否有适用于所有我缺少的数字类型(int、double、float...)的通用接口???

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,那么我有一个 泛型运算符实现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).

这有诸如 T Add(T x, T y) 之类的方法,以及用于不同类型算术的其他变体(例如 DateTime + TimeSpan).

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.

您可能还想知道 dynamic (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

<小时>

关于 </> 的评论 - 你实际上并不需要操作符;你只需要:


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆