我有一个像这样的枚举结构:
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);
使用nameof
表达式,是最快的编译时解决方案。
返回枚举类型的字面量大小写或在其他情况下返回class
、struct
或任何类型的variable
(arg、param、local等)。
public enum MyEnum {
CSV,
Excel
}
string enumAsString = nameof(MyEnum.CSV)
// enumAsString = "CSV"
注意:
nameof
区分大小写的特性。你只需要进行强制类型转换即可
int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible
啊..肯特比我先发了 :)
解决方案:
int enumValue = 2; // The value for which you want to get string
string enumName = Enum.GetName(typeof(EnumDisplayStatus), enumValue);
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
数据库转C#
EnumDisplayStatus status = (EnumDisplayStatus)int.Parse(GetValueFromDb());
C# 到数据库
string dbStatus = ((int)status).ToString();
给定:
enum Colors {
Red = 1,
Green = 2,
Blue = 3
};
Console.WriteLine( Enum.GetName( typeof(Colors), Colors.Green ) );
Console.WriteLine( Enum.GetName( typeof(Colors), 3 ) );
将显示
Green
Blue
Console.WriteLine( Enum.GetName( Colors.Green ) );
Console.WriteLine( Enum.GetName( (Colors)3 ) );
将显示:
Green
Blue
只需要:
string stringName = EnumDisplayStatus.Visible.ToString("f");
// stringName == "Visible"
enum Foo { A = 1, B= 1 }
的行为是什么? - dbkk