Страницы

Поиск по вопросам

четверг, 12 декабря 2019 г.

Преобразовать int в enum

#c_sharp #преобразование #enum


Как можно преобразовать int в enum в C#-e?
    


Ответы

Ответ 1



Из int: CustomEnum enm = (CustomEnum)number; Можно еще и: CustomEnum enm = (CustomEnum)Enum.ToObject(typeof(CustomEnum), number); Из string: CustomEnum enm = (CustomEnum)Enum.Parse(typeof(CustomEnum), str);

Ответ 2



Прежде чем преобразовывать число в перечисление необходимо проверить, принадлежит ли число перечислению, чтобы не выйти за пределы enum и не получить неожиданного поведения кода из-за непредвиденного значения: int number = 1; if (Enum.IsDefined(typeof(CustomEnum), number)) { CustomEnum enm = (CustomEnum)number; // преобразование // или CustomEnum enm = (CustomEnum)Enum.ToObject(typeof(CustomEnum), number); } Документация на MSDN: Enum.IsDefined enum (C# Reference) Enumeration Types (C# Programming Guide) Enum.TryParse Из примера документации на MSDN: using System; [Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 }; public class Example { public static void Main() { string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; foreach (string colorString in colorStrings) { Colors colorValue; if (Enum.TryParse(colorString, out colorValue)) if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(",")) Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString()); else Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString); else Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString); } } } // The example displays the following output: // Converted '0' to None. // Converted '2' to Green. // 8 is not an underlying value of the Colors enumeration. // blue is not a member of the Colors enumeration. // Converted 'Blue' to Blue. // Yellow is not a member of the Colors enumeration. // Converted 'Red, Green' to Red, Green. В примере имеет место проверка Enum.IsDefined. Обезопасить свой код от возможных ошибок - не является признаком плохого тона программирования, я так думаю.

Комментариев нет:

Отправить комментарий