在這裏,我們將了解 Enum Class 的 CompareTo() 方法。此方法用於將實例與特定的枚舉對象進行比較。
用法:
int Enum.CompareTo(Enum obj);
參數:
- obj:它是一個將與枚舉的當前實例進行比較的對象。
返回值:
此方法返回一個整數值,指定兩個枚舉對象的比較。
- 0:兩者相等
- >0:當前對象大於指定對象。
- <0:當前對象小於指定對象。
異常:
- System.ArgumentException
- System.InvalidOperationException
- System.NullReferenceException
程序:
下麵給出了演示使用 Enum 類的 CompareTo() 方法的源代碼。給定的程序已成功編譯並執行。
using System;
class Sample
{
enum Color { RED=0,GREEN=1,YELLOW=3,WHITE=4,BLACK=5};
//Entry point of Program
static public void Main()
{
Color firstColor = Color.RED;
Color secondColor = Color.WHITE;
Color thirdColor = Color.BLACK;
if (firstColor.CompareTo(secondColor) > 0)
Console.WriteLine("FirstColor is greater than SecondColor");
else
Console.WriteLine("SecondColor is greater than FirstColor");
if (secondColor.CompareTo(thirdColor) > 0)
Console.WriteLine("SecondColor is greater than ThirdColor");
else
Console.WriteLine("ThirdColor is greater than SecondColor");
}
}
輸出:
SecondColor is greater than FirstColor ThirdColor is greater than SecondColor Press any key to continue . . .
相關用法
- C# Enum Equals()用法及代碼示例
- C# Enum ToObject()用法及代碼示例
- C# Enum Format()用法及代碼示例
- C# Enum Parse()用法及代碼示例
- C# Environment GetEnvironmentVariable()用法及代碼示例
- C# Environment GetCommandLineArgs()用法及代碼示例
- C# Environment FailFast()用法及代碼示例
- C# Environment Exit()用法及代碼示例
- C# Decimal.FromOACurrency()用法及代碼示例
- C# Int32.CompareTo用法及代碼示例
- C# File.WriteAllLines(String, IEnumerable<String>)用法及代碼示例
- C# Type.GetTypeHandle()用法及代碼示例
- C# Uri.IsBaseOf()用法及代碼示例
- C# String.ToUpperInvariant用法及代碼示例
- C# File.Copy(String, String, Boolean)用法及代碼示例
- C# Uri.IsHexEncoding()用法及代碼示例
- C# Char.TryParse()用法及代碼示例
- C# Math Cosh()用法及代碼示例
- C# Int64.Equals用法及代碼示例
- C# Convert.ToInt16(String, IFormatProvider)用法及代碼示例
注:本文由純淨天空篩選整理自 C# program to demonstrate the use of CompareTo() method of Enum class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。