Convert integer to Enum instance

public void EnumInstanceFromInt()
{
// The .NET Framework contains an Enum called DayOfWeek.
// Let’s generate some Enum instances from int values.

// Usually you wouldn’t cast an instance of an existing Enum to an int
// in order to create an Enum instance. :-) You would have the actual
// integer value, perhaps a value from a database where the int value of
// the enum was stored.

DayOfWeek wednesday =
(DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Wednesday);
DayOfWeek sunday =
(DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Sunday);
DayOfWeek tgif =
(DayOfWeek)Enum.ToObject(typeof(DayOfWeek), (int)DayOfWeek.Friday);

lblOutput.Text = wednesday.ToString()
+ “. Int value = ” + ((int)wednesday).ToString() + “\n”;
lblOutput.Text += sunday.ToString()
+ “. Int value = ” + ((int)sunday).ToString() + “\n”;
lblOutput.Text += tgif.ToString()
+ “. Int value = ” + ((int)tgif).ToString() + “\n”;
}

Result:

Wednesday. Int value = 3
Sunday. Int value = 0
Friday. Int value = 5

Link: http://www.cambiaresearch.com/c4/52a7e5fe-c7fc-49ab-b21d-37e6194687f3/Convert-Integer-To-Enum-Instance-in-csharp.aspx

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>