算术运算符重载在C#泛型类

算术运算符重载在C#泛型类

问题描述:

给出一个泛型类定义,就像

Given a generic class definition like

public class ConstrainedNumber<T> :
    IEquatable<ConstrainedNumber<T>>,
    IEquatable<T>,
    IComparable<ConstrainedNumber<T>>,
    IComparable<T>,
    IComparable where T:struct, IComparable, IComparable<T>, IEquatable<T>

如何定义算术运算符呢?

How can I define arithmetic operators for it?

下面无法编译,因为+操作​​符不能应用于类型的'T'和'T':

The following does not compile, because the '+' operator cannot be applied to types 'T' and 'T':

public static T operator +( ConstrainedNumber<T> x, ConstrainedNumber<T> y)
{
    return x._value + y._value;
}

泛型类型T被约束的',其中'关键字就像你看到的,但我需要有算术运算符号码类型约束(IArithmetic?)。

The generic type 'T' is constrained with the 'where' keyword as you can see, but I need a constraint for number types that have arithmetic operators (IArithmetic?).

'T'将是一个原始的号码类型,如整型,浮点等是否有一个',其中'约束这样的类型?

'T' will be a primitive number type such as int, float, etc. Is there a 'where' constraint for such types?

我认为最好的你可以做的是使用 IConvertible 作为约束,做一些这样的:

I think the best you'd be able to do is use IConvertible as a constraint and do something like:

 public static operator T +(T x, T y)
    where T: IConvertible
{
    var type = typeof(T);
    if (type == typeof(String) ||
        type == typeof(DateTime)) throw new ArgumentException(String.Format("The type {0} is not supported", type.FullName), "T");

    try { return (T)(Object)(x.ToDouble(NumberFormatInfo.CurrentInfo) + y.ToDouble(NumberFormatInfo.CurrentInfo)); }
    catch(Exception ex) { throw new ApplicationException("The operation failed.", ex); }
}

这不会在一个字符串或日期时间虽然通过阻止别人,所以你可能需要做一些手动检查 - 但IConvertible应该让你足够接近,并让你做手术

That won't stop someone from passing in a String or DateTime though, so you might want to do some manual checking - but IConvertible should get you close enough, and allow you to do the operation.