给定一个通用的类定义,如
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/