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

C#中泛型类的算术运算符重载,第1张

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

我认为您能够做的最好的事情就是将其

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应该使您足够接近,并允许您执行 *** 作。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4912019.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存