首页 > 解决方案 > TimeSpan 中的冗余方法

问题描述

当我使用TimeSpan类时,有一个Add()扩展方法

public TimeSpan Add(TimeSpan ts) {
  long result = _ticks + ts._ticks;
  // Overflow if signs of operands was identical and result's
  // sign was opposite.
  // >> 63 gives the sign bit (either 64 1's or 64 0's).
  if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
       throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
   return new TimeSpan(result);
}

基本上它与+操作员的作用相同。

public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) {
    return t1.Add(t2);
}

添加值并在溢出的情况下引发异常。

问题:

为什么.NET提供这个方法?不会

public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)

足够的?egint也没有提供Add方法。

标签: c#operator-overloadingtimespan

解决方案


推荐阅读