.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?
推荐答案
没有立即回答;运算符是静态的,并且不能在约束中表示 - 并且现有的原语不实现任何特定的接口(与可以用于模拟大于/小于的模拟的[13]的对比)。
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屋!