สารละลาย:
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
nameof(EnumDisplayStatus.Visible)
หวังว่าจะช่วยให้ใครซักคน