當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Enum Format()用法及代碼示例

在這裏,我們將了解 Enum 類的 Format() 方法。該方法用於將枚舉的指定值按照指定的格式轉換為字符串。

用法:

    string Enum.Format(Type enumType, object value, string format);

參數:

  • enumType:類型是枚舉。
  • value:枚舉對象。
  • format:Format 將枚舉值表示為指定的字符串格式。

返回值:

此方法根據指定的格式返回字符串值。

異常:

  • System.ArgumentException
  • System.ArgumentNullException
  • System.InvalidOperationException
  • System.FormatException

程序:

下麵給出了演示使用 Enum 類的 Format() 方法的源代碼。給定的程序已成功編譯並執行。

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.GREEN;
        Color secondColor   = Color.WHITE;

        string strValue = "";

        strValue = Enum.Format(typeof(Color), firstColor, "d");
        Console.WriteLine(strValue);

        strValue = Enum.Format(typeof(Color), secondColor, "x");

        Console.WriteLine(strValue);
    }
}

輸出:

1
00000004
Press any key to continue . . .



相關用法


注:本文由純淨天空篩選整理自 C# program to demonstrate the use of Format() method of Enum class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。