Posts Tagged ‘C#

Convert integer to Enum instance

2008年10月27日 星期一

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