.NET泛型中重载运算符约束的解决方案 [英] Solution for overloaded operator constraint in .NET generics
问题描述
如果我想要一个泛型方法只接受重载运算符的类型,例如减法运算符,我该怎么办.我尝试使用接口作为约束,但接口不能有运算符重载.
What would I do if I want to have a generic method that only accepts types that have overloaded an operator, for instance the subtraction operator. I tried using an interface as a constraint but interfaces can't have operator overloading.
实现这一目标的最佳方法是什么?
What is the best way to achieve this?
推荐答案
没有立即答复;操作符是静态的,不能用约束来表达 - 现有的原语没有实现任何特定的接口(与 IComparable[<T>] 相反,它可用于模拟大于/小于).
There is no immediate answer; operators are static, and cannot be expressed in constraints - and the existing primatives don't implement any specific interface (contrast to IComparable[<T>] which can be used to emulate greater-than / less-than).
然而;如果你只是想让它工作,那么在 .NET 3.5 中有一些选项......
However; if you just want it to work, then in .NET 3.5 there are some options...
我在这里整理了一个库以及使用泛型简单访问运算符 - 例如:
I have put together a library here that allows efficient and simple access to operators with generics - such as:
T result = Operator.Add(first, second); // implicit <T>; here
它可以作为 MiscUtil
此外,在 C# 4.0 中,这可以通过 dynamic
实现:
Additionally, in C# 4.0, this becomes possible via dynamic
:
static T Add<T>(T x, T y) {
dynamic dx = x, dy = y;
return dx + dy;
}
我也有(曾经)一个 .NET 2.0 版本,但测试较少.另一种选择是创建一个接口,例如
I also had (at one point) a .NET 2.0 version, but that is less tested. The other option is to create an interface such as
interface ICalc<T>
{
T Add(T,T)()
T Subtract(T,T)()
}
等,但随后您需要通过所有方法传递 ICalc
,这会变得混乱.
etc, but then you need to pass an ICalc<T>;
through all the methods, which gets messy.
这篇关于.NET泛型中重载运算符约束的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!