影片內用 Enum.GetName() 和 ToString() 兩種方法取出 Enum String 值
MVA 範例
class Program
{
static void Main(string[] args)
{
// Enum.GetName()
AuthMethod auth = AuthMethod.FORMS;
string str1 = Enum.GetName(typeof(AuthMethod), auth);
Console.WriteLine(str1);
// ToString()
string str2 = AuthMethod.WINDOWSAUTHENTICATION.ToString();
Console.WriteLine(str2);
}
public enum AuthMethod
{
FORMS = 1,
WINDOWSAUTHENTICATION = 2,
SINGLESIGNON = 3
}
}
練習時發現原來 enum string 中,不能有空白,搜尋些資料才發現 enum 可以設定 Description
using System.ComponentModel;
using System.Reflection;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
foreach (enumProductions Production in Enum.GetValues(typeof(enumProductions)))
{
FieldInfo fi = Production.GetType().GetField(Production.ToString());
if (fi == null) return;
object[] attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute),true);
if (attrs != null && attrs.Length > 0) Console.WriteLine(((DescriptionAttribute)attrs[0]).Description);
}
}
enum enumProductions
{
[Description("SQL Server")]
SQLServer = 1 ,
[Description("Visual Studio")]
VisualStudio = 2 ,
[Description("Windows Server")]
WindowsServer = 3
}
}
}
沒有留言:
張貼留言