我有一个像这样的枚举构造:
public enum EnumDisplayStatus { None = 1, Visible = 2, Hidden = 3, MarkedForDeletion = 4 }
在我的数据库中,枚举由值引用.我的问题是,如何将枚举的数字表示形式转回字符串名称.
例如,给定2
结果应该是Visible
.
您可以int
使用简单的强制转换将其转换为枚举成员,然后调用ToString()
:
int value = GetValueFromDb(); var enumDisplayStatus = (EnumDisplayStatus)value; string stringValue = enumDisplayStatus.ToString();
如果您需要获取字符串"Visible"
而不获取EnumDisplayStatus
实例,则可以执行以下操作:
int dbValue = GetDBValue(); string stringValue = Enum.GetName(typeof(EnumDisplayStatus), dbValue);
试试这个:
string m = Enum.GetName(typeof(MyEnumClass), value);
用这个:
string bob = nameof(EnumDisplayStatus.Visible);
你可以施展它
int dbValue = 2; EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue; string stringName = enumValue.ToString(); //Visible
啊..肯特打败了我:)
DB到C#
EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());
C#到DB
string dbStatus = ((int)status).ToString();
解:
int enumValue = 2; // The value for which you want to get string string enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);
同样,使用GetName优于Enum的显式转换。
[绩效基准代码]
Stopwatch sw = new Stopwatch (); sw.Start (); sw.Stop (); sw.Reset (); double sum = 0; int n = 1000; Console.WriteLine ("\nGetName method way:"); for (int i = 0; i < n; i++) { sw.Start (); string t = Enum.GetName (typeof (Roles), roleValue); sw.Stop (); sum += sw.Elapsed.TotalMilliseconds; sw.Reset (); } Console.WriteLine ($"Average of {n} runs using Getname method casting way: {sum / n}"); Console.WriteLine ("\nExplicit casting way:"); for (int i = 0; i < n; i++) { sw.Start (); string t = ((Roles)roleValue).ToString (); sw.Stop (); sum += sw.Elapsed.TotalMilliseconds; sw.Reset (); } Console.WriteLine ($"Average of {n} runs using Explicit casting way: {sum / n}");
[样品结果]
GetName method way: Average of 1000 runs using Getname method casting way: 0.000186899999999998 Explicit casting way: Average of 1000 runs using Explicit casting way: 0.000627900000000002