📜  C#中的TimeSpan.Add()方法

📅  最后修改于: 2021-05-29 15:26:45             🧑  作者: Mango

此方法用于获取新的TimeSpan对象,该对象的值是指定的TimeSpan对象与该实例的和。

异常OverflowException :当生成的TimeSpan小于最小可能值或大于最大可能值时发生。

下面的程序说明了TimeSpan.Add(TimeSpan)方法的用法:

范例1:

// C# program to demonstrate the
// TimeSpan.Add(TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // creating the TimeSpan object
            TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
            TimeSpan t2 = new TimeSpan(1, 11, 15, 16);
            TimeSpan variable = t1.Add(t2);
  
            Console.WriteLine("The Timespan is : {0}",
                                            variable);
        }
  
        catch (OverflowException e) 
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
The Timespan is : 5:09:50:49

示例2:对于溢出异常

// C# program to demonstrate the
// TimeSpan.Add(TimeSpan) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // the TimeSpan object
            TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
            TimeSpan t2 = TimeSpan.MaxValue;
            TimeSpan variable = t1.Add(t2);
  
            Console.WriteLine("The Timespan is : {0}",
                                            variable);
        }
  
        catch (OverflowException e)
        {
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
Exception Thrown: System.OverflowException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.timespan.add?view=netframework-4.7.2