问题描述
给定一个像
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"受where"关键字约束,但我需要对具有算术运算符(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' 将是原始数字类型,例如 int、float 等.此类类型是否有where"约束?
'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.
这篇关于C#中泛型类的算术运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!