Giới thiệu
Phương thức Add() của TimeSpan cộng một TimeSpan khác vào instance hiện tại và trả về TimeSpan mới (immutable).
Ví dụ cơ bản
TimeSpan t1 = TimeSpan.FromMinutes(1); TimeSpan t2 = TimeSpan.FromMinutes(2); TimeSpan res = t1.Add(t2); // 3 phút
Ví dụ hoàn chỉnh
using System;
public class Demo
{
public static void Main()
{
TimeSpan t1 = TimeSpan.FromMinutes(1);
TimeSpan t2 = TimeSpan.FromMinutes(2);
Console.WriteLine("First TimeSpan: " + t1);
Console.WriteLine("Second TimeSpan: " + t2);
TimeSpan res = t1.Add(t2);
Console.WriteLine("Resultant TimeSpan: " + res);
}
}
Kết quả
First TimeSpan: 00:01:00 Second TimeSpan: 00:02:00 Resultant TimeSpan: 00:03:00
Toán tử cộng (+)
C# nạp chồng toán tử + cho TimeSpan:
TimeSpan res = t1 + t2; // Tương đương t1.Add(t2)
Các phương thức liên quan
Subtract(TimeSpan)/ toán tử-: Trừ TimeSpan.Negate(): Đổi dấu (âm thành dương, dương thành âm).Duration(): Giá trị tuyệt đối (|TimeSpan|).
Lưu ý
- TimeSpan là immutable -
Add()trả về instance mới, không sửa đổi t1. - Kết quả có thể vượt quá
TimeSpan.MaxValue-> némOverflowException. - Dùng
checkedcontext nếu muốn bắt overflow rõ ràng.
Ví dụ thực tế: Tổng thời gian thực thi nhiều task
TimeSpan total = TimeSpan.Zero;
foreach (var task in tasks)
{
Stopwatch sw = Stopwatch.StartNew();
task.Execute();
sw.Stop();
total = total.Add(sw.Elapsed);
}
Console.WriteLine($"Tổng thời gian: {total}");