c# - C# 中泛型类的算术运算符重载

标签 c# generics operator-overloading math primitive-types

给定一个通用的类定义,如

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

如何为其定义算术运算符?

以下代码无法编译,因为“+”运算符不能应用于类型“T”和“T”:

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

如您所见,通用类型“T”受“where”关键字约束,但我需要对具有算术运算符(IArithmetic?)的数字类型进行约束。

'T' 将是原始数字类型,例如 int、float 等。这些类型是否有“where”约束?

最佳答案

我认为你能做的最好的事情就是使用 IConvertible 作为约束并做类似的事情:

 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); }
}

虽然这不会阻止某人传递 String 或 DateTime,因此您可能想要进行一些手动检查 - 但 IConvertible 应该让您足够接近,并允许您执行操作。

关于c# - C# 中泛型类的算术运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/756954/

相关文章:

c++ - 两个相同的重载运算符 [] 一个返回引用

c# - C# 中的受约束泛型委托(delegate)

c# - 使用通配符或 "tags"进行用户输入

c++ - 调用 const 函数而不是其非 const 版本

java - 如何定义一个灵活接受声明类型的子类的函数

c# - 我可以采用 string 或 IEnumerable<T>,其中 T 是 string 或 IEnumerable<T> 吗?

c++ - 无法将函数定义与模板化类中的现有定义相匹配

c# - 通过 JInt 检查有效的 jQuery 代码时出现 "document is not defined"错误?

c# - Windows Phone 7.1 模拟器不加载应用程序

java - 列表是原始类型。对泛型类型 List<E> 的引用应该被参数化