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.

 

Try and Catch

The try and catch keywords are used together. Use try to enclose the block of code you are concerned might generate an exception, and catch to contain the code that will be executed if the exception occurs. In this example, a calculation creates a division by zero exception, which is then caught. Without the try and catch blocks, this program would fail.

class ProgramTryCatch { static void Main() { int x=0, y=0;   try { x = 10 / y; } catch (System.DivideByZeroException) { System.Console.WriteLine("There was an attempt to divide by zero."); } } }

It's good programming practice to be specific about the type of exception your catch code is detecting. Each try can have multiple catch statements, each dealing with a different exception.




Дата добавления: 2022-05-27; просмотров: 121;


Поиск по сайту:

Воспользовавшись поиском можно найти нужную информацию на сайте.

Поделитесь с друзьями:

Считаете данную информацию полезной, тогда расскажите друзьям в соц. сетях.
Poznayka.org - Познайка.Орг - 2016-2024 год. Материал предоставляется для ознакомительных и учебных целей.
Генерация страницы за: 0.056 сек.