logo
Учебник_ПОА

More Advanced Enumeration Techniques

Here are several more features of enum data types that might be useful.

Displaying the Enumeration's Literal Values

If you need to access the name or words you are using in your enum data type, you can do so using the ToString() method, as follows:

DayOfWeek day = DayOfWeek.Wednesday;

System.Console.WriteLine(day.ToString()); // displays Wednesday

Setting the Default Values

By default, the first value in the enumerated type is a zero. You can specify a different initial value, as follows:

enum Color { Red = 1, Yellow = 2, Blue = 3 };

In fact, you can define unique integer values for all the values:

enum Medal { Gold = 30, Silver = 20, Bronze = 10 };

Дополнительные способы перечисления

Далее представлено несколько дополнительных функций типов данных enum, которые могут быть полезны.

Отображение значений литералов перечисления

Для доступа к имени или словам, используемым в типе данных enum можно применить метод ToString(), как показано далее.

DayOfWeek day = DayOfWeek.Wednesday;

System.Console.WriteLine(day.ToString()); // displays Wednesday

Установка значений по умолчанию

По умолчанию первым значением в перечисляемом типе является ноль. Можно указать другое начальное значение, как показано далее.

enum Color { Red = 1, Yellow = 2, Blue = 3 };

Фактически, можно определить уникальные целочисленные значения для всех значений.

enum Medal { Gold = 30, Silver = 20, Bronze = 10 };

Errors and Exception Handling

When something goes wrong while a C# program is running, an exception occurs. Exceptions stop the current flow of the program, and if nothing is done, the program simply stops running. Exceptions can be caused by a bug in the program — for example, if a number is divided by zero — or can be a result of some unexpected input, such as a user selecting a file that doesn't exist. As a programmer, you need to allow your program to deal with these problems without crashing to a halt.

C# provides several keywords — try, catch, and finally — that allow programs to detect exceptions, deal with them, and continue running. They are a very useful tool for making your applications more reliable.