在這裏,我們將了解 Enum 類的 Parse() 方法。此方法用於將一個或多個枚舉常量的名稱或數值的字符串表示形式轉換為等效的枚舉對象。這是兩次重載的方法。
用法:
object Enum.Parse(Type enumType, string value); object Enum.Parse(Type enumType, string value, bool ignoreCase);
參數:
- enumType:枚舉對象的類型。
- value:要解析的字符串值。
- ignoreCase:它指定操作是否區分大小寫。
返回值:
此方法根據傳遞的值返回解析的對象。
異常:
- System.OverflowExcetion
- System.ArgumentException
- System.ArgumentNullException
程序:
下麵給出了演示使用 Enum 類的 Parse() 方法的源代碼。給定的程序已成功編譯並執行。
using System;
class Sample
{
enum Directions { EAST=0,WEST=1,NORTH=2,SOUTH=3};
//Entry point of Program
static public void Main()
{
Directions dir;
//Parse string to objects then
//we convert it to Enum objects
dir = (Directions)Enum.Parse(typeof(Directions), "1");
Console.WriteLine(Enum.GetName(typeof(Directions),dir));
//Parse string to objects then
//we convert it to Enum objects with ignore case
dir = (Directions)Enum.Parse(typeof(Directions), "3",true);
Console.WriteLine(Enum.GetName(typeof(Directions), dir));
}
}
輸出:
WEST SOUTH Press any key to continue . . .
相關用法
- C# Enum Equals()用法及代碼示例
- C# Enum CompareTo()用法及代碼示例
- C# Enum ToObject()用法及代碼示例
- C# Enum Format()用法及代碼示例
- 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 Parse() method of Enum class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。