此方法用于比较两个TimeSpan值,并返回一个整数值,该整数值指示第一个值是小于,等于还是大于第二个值。
Syntax: public static int Compare (TimeSpan t1, TimeSpan t2);
Paramaters:
t1: Specifies the first time interval that will be compared.
t2: Specifies the second time interval that will be compared.
Return Value:
-1: If t1 is shorter than t2.
0: If t1 is equal to t2.
1: If t1 is longer than t2.
下面的程序说明了TimeSpan.Compare(TimeSpan,TimeSpan)方法的用法:
范例1:
// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan,
// TimeSpan) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// creating the TimeSpans
TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
TimeSpan t2 = new TimeSpan(1, 11, 15, 16);
if (TimeSpan.Compare(t1, t2) == 1)
Console.Write("t1 is greater than t2");
else if (TimeSpan.Compare(t1, t2) == 0)
Console.Write("t1 is equal to t2");
else
Console.Write("t2 is greater than t1");
}
}
输出:
t1 is greater than t2
范例2:
// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan,
// TimeSpan) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// creating the TimeSpans
TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
TimeSpan t2 = new TimeSpan(4, 31, 15, 10);
if (TimeSpan.Compare(t1, t2) == 1)
Console.Write("t1 is greater than t2");
else if (TimeSpan.Compare(t1, t2) == 0)
Console.Write("t1 is equal to t2");
else
Console.Write("t2 is greater than t1");
}
}
输出:
t2 is greater than t1
范例3:
// C# program to demonstrate the
// TimeSpan.Compare(TimeSpan,
// TimeSpan) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// creating the TimeSpans
TimeSpan t1 = new TimeSpan(3, 22, 35, 33);
TimeSpan t2 = new TimeSpan(3, 22, 35, 33);
if (TimeSpan.Compare(t1, t2) == 1)
Console.Write("t1 is greater than t2");
else if (TimeSpan.Compare(t1, t2) == 0)
Console.Write("t1 is equal to t2");
else
Console.Write("t2 is greater than t1");
}
}
输出:
t1 is equal to t2
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.timespan.compare?view=netframework-4.7.2