Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 13 ENUMERATIONS

More About Enums

Enums have only a single member type: the declared member constants.

You cannot use modifiers with the members. They all implicitly have the same accessibility as the enum.

Since the members are static, they are accessible even if there are no variables of the enum type. Use the enum type name, followed by a dot and the member name.

For example, the following code does not create any variables of the enum TrafficLight type, but the members are accessible and can be printed using WriteLine.

static void Main()

 

 

 

 

{

Console.WriteLine("{0}", TrafficLight.Green);

 

 

Console.WriteLine("{0}", TrafficLight.Yellow);

 

Console.WriteLine("{0}", TrafficLight.Red);

}

 

 

 

 

 

 

Enum name

Member name

339

CHAPTER 13 ENUMERATIONS

An enum is a distinct type. Comparing enum members of different enum types results in a compiletime error. For example, the following code declares two enum types.

The first if statement is fine because it compares different members from the same enum type.

The second if statement produces an error because it compares members from different enum types, even though their structures and member names are exactly the same.

enum FirstEnum

// First enum type

{

 

Mem1,

 

Mem2

 

}

 

enum SecondEnum

// Second enum type

{

 

Mem1,

 

Mem2

 

}

 

class Program

 

{

 

static void Main()

 

{

 

if (FirstEnum.Mem1 < FirstEnum.Mem2) // OK--members of same enum type Console.WriteLine("True");

if (FirstEnum.Mem1 < SecondEnum.Mem1) // Error--different enum types Console.WriteLine("True");

}

}

340

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]