Csharp/CSharp Tutorial/Data Type/enum

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Assign enum value from a member and variable

<source lang="csharp">using System; enum Color {

  Green,
  Yellow,
  Red

} class MainClass {

  static void Main()
  {
     Color t1 = Color.Red;     
     Color t2 = Color.Green;   
     Color t3 = t2;                   
     Console.WriteLine(t1);
     Console.WriteLine(t2);
     Console.WriteLine(t3);
  }

}</source>

Red
Green
Green

Assign int value to enumerations

<source lang="csharp">using System; enum Values {

   A = 1,
   B = 5,
   C = 3,
   D = 42

} class MainClass {

   public static void Main()
   {
       Values v = (Values) 2;
       int ival = (int) v;
   }

}</source>

Declaration of enum data type

<source lang="csharp">using System; enum DaysOfWeek {

 Monday,
 Tuesday,
 Wednesday,
 Thursday,
 Friday,
 Saturday,
 Sunday

} class MainClass {

 static void Main(string[] args)
 {
   DaysOfWeek Today = DaysOfWeek.Monday;
   Console.WriteLine(Today);
 }

}</source>

Monday

Define constants with const keywords and enum

<source lang="csharp">using System; enum MyEnum {

   A

} class Constants {

   public const MyEnum value3 = MyEnum.A;

} class MainClass {

   public static void Main()
   {
       Console.WriteLine("{0}", Constants.value3);
   }

}</source>

A

Enumerations

  1. An enumeration is a set of named integer constants.
  2. The keyword enum declares an enumerated type.

The general form for an enumeration is


<source lang="csharp">enum name {

   enumeration list 

};</source>

  1. name specifies the enumeration type name.
  2. enumeration list is a comma-separated list of identifiers.
  1. Each of the symbols stands for an integer value.
  2. Each of the symbols has a value one greater than the symbol that precedes it.
  3. By default, the value of the first enumeration symbol is 0.

Enumerations Initialization with calculation

<source lang="csharp">using System; enum Values {

   A = 1,
   B = 2,
   C = A + B,
   D = A * C + 33

} class MainClass {

   public static void Member(Values value)
   {
       Console.WriteLine(value);
   }
   public static void Main()
   {
       Values value = 0;
       Member(value);
   }

}</source>

0

Enumerations Initialization with integer value

<source lang="csharp">enum Values {

   A = 1,
   B = 5,
   C = 3,
   D = 42

}</source>

Loop through the enum data type

<source lang="csharp">using System;

class MainClass {

 enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturaday,Sunday }; 

 public static void Main() { 
   Week i;

   for(i = Week.Monday; i <= Week.Sunday; i++)  
     Console.WriteLine(i + " has value of " + (int)i); 

 } 

}</source>

Monday has value of 0
Tuesday has value of 1
Wednesday has value of 2
Thursday has value of 3
Friday has value of 4
Saturaday has value of 5
Sunday has value of 6

Output enum element value

<source lang="csharp">using System; enum Color {

   red,
   green,
   yellow

} public class MainClass {

   public static void Main()
   {
       Color c = Color.red;
       
       Console.WriteLine("c is {0}", c);
   }

}</source>

c is red

Pass enum data to a method

<source lang="csharp">using System;

public enum LineStyle {

   Solid,
   Dotted,
   DotDash,

}

class MainClass {

   public static void Main()
   {
       DrawLine(LineStyle.Solid);
       DrawLine((LineStyle) 35);
   }
   public static void DrawLine(LineStyle lineStyle)
   {
       switch (lineStyle)
       {
           case LineStyle.Solid:
               Console.WriteLine("draw solid");
               break;
           
           case LineStyle.Dotted:
               Console.WriteLine("draw dotted");
               break;
           
           case LineStyle.DotDash:
               Console.WriteLine("draw dotdash");
               break;
           
           default:
               throw(new ArgumentException("Invalid line style"));
       }
   }
   

}</source>

draw solid
Unhandled Exception: System.ArgumentException: Invalid line style
   at MainClass.DrawLine(LineStyle lineStyle)
   at MainClass.Main()

Print out the details of any enum

<source lang="csharp">using System; using System.Collections.Generic; using System.Text;

 enum EmpType : byte
 {
   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VicePresident = 9
 }
 class Program
 {
   static void Main(string[] args)
   {
     EmpType e2 = EmpType.Contractor;
     DayOfWeek day = DayOfWeek.Friday;
     ConsoleColor cc = ConsoleColor.Black;
     EvaluateEnum(e2);
     EvaluateEnum(day);
     EvaluateEnum(cc);
   }
   static void EvaluateEnum(System.Enum e)
   {
     Console.WriteLine("=> Information about {0}", e.GetType().Name);
     Console.WriteLine("Underlying storage type: {0}",Enum.GetUnderlyingType(e.GetType()));
     Array enumData = Enum.GetValues(e.GetType());
     Console.WriteLine("This enum has {0} members.", enumData.Length);
     for (int i = 0; i < enumData.Length; i++)
     {
       Console.WriteLine("Name: {0}, Value: {0:D}", enumData.GetValue(i));
     }
   }
 }</source>

Readonly Fields with enum

<source lang="csharp">public enum ColorEnum {

   Red,
   Blue,
   Green

} class Color {

   public Color(int red, int green, int blue)
   {
       this.red = red;
       this.green = green;
       this.blue = blue;
   }
   
   public static Color GetPredefinedColor(ColorEnum pre)
   {
       switch (pre)
       {
           case ColorEnum.Red:
              return(new Color(255, 0, 0));
           
           case ColorEnum.Green:
              return(new Color(0, 255, 0));
           
           case ColorEnum.Blue:
              return(new Color(0, 0, 255));
           
           default:
              return(new Color(0, 0, 0));
       }
   }
   int red;
   int blue;
   int green;

} class MainClass {

   static void Main()
   {
       Color background = Color.GetPredefinedColor(ColorEnum.Blue);
   }

}</source>

Use an enumeration to index an array

<source lang="csharp">using System;

class MainClass {

 enum Week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturaday,Sunday }; 

 public static void Main() { 
   Week i;

   
   for(i = Week.Monday; i <= Week.Sunday; i++)  
     Console.WriteLine("Color of " + i + " is "+ (int)i); 

 } 

}</source>

Color of Monday is 0
Color of Tuesday is 1
Color of Wednesday is 2
Color of Thursday is 3
Color of Friday is 4
Color of Saturaday is 5
Color of Sunday is 6

Use enum data as flags

<source lang="csharp">using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; [Flags] enum FileAccess {

   Read = 1,
   Write = 2,
   ReadWrite = 3

}

public class MainClass {

  public static void Main(){
       FileAccess rw1 = FileAccess.Read | FileAccess.Write;
       Console.WriteLine("rw1 == {0}", rw1);
       FileAccess rw2 = FileAccess.ReadWrite;
       Console.WriteLine("rw2 == {0}", rw2);
       Console.WriteLine("rw1 == rw2? {0}", rw1 == rw2);
       if (rw1 == FileAccess.Read)
           Console.WriteLine("try #1: read permitted");
       else
           Console.WriteLine("try #1: read denied");
       if ((rw2 & FileAccess.Read) != 0)
           Console.WriteLine("try #2: read permitted");
       else
           Console.WriteLine("try #2: read denied");
  }

}</source>

rw1 == ReadWrite
rw2 == ReadWrite
rw1 == rw2? True
try #1: read denied
try #2: read permitted

Use enum type categorize objects

<source lang="csharp">using System; enum EmployeeTypeEnum {

   Employee,
   Manager

} class Employee {

   public Employee(string name, float billingRate)
   {
       this.name = name;
       this.billingRate = billingRate;
       type = EmployeeTypeEnum.Employee;
   }
   
   public float CalculateCharge(float hours)
   {
       if (type == EmployeeTypeEnum.Manager)
       {
           Manager c = (Manager) this;
           return(c.CalculateCharge(hours));
       }
       else if (type == EmployeeTypeEnum.Employee)    
           return(hours * billingRate);
       return(0F);
   }
   
   public string TypeName()
   {
       if (type == EmployeeTypeEnum.Manager)
       {
           Manager c = (Manager) this;
           return(c.TypeName());
       }
       else if (type == EmployeeTypeEnum.Employee)
           return("Employee");
       return("No Type Matched");
   }
   
   private string name;
   protected float billingRate;
   protected EmployeeTypeEnum type;

} class Manager: Employee {

   public Manager(string name, float billingRate) :
   base(name, billingRate)
   {
       type = EmployeeTypeEnum.Manager;
   }
   
   public new float CalculateCharge(float hours)
   {
       if (hours < 1.0F)
       hours = 1.0F;        // minimum charge.
       return(hours * billingRate);
   }
   
   public new string TypeName()
   {
       return("Civil Employee");
   }

} class MainClasss{

   public static void Main(){
       Employee[]    earray = new Employee[2];
       earray[0] = new Employee("A", 15.50F);
       earray[1] = new Manager("B", 40F);
       
       Console.WriteLine("{0} charge = {1}",
       earray[0].TypeName(),
       earray[0].CalculateCharge(2F));
       Console.WriteLine("{0} charge = {1}",
       earray[1].TypeName(),
       earray[1].CalculateCharge(0.75F));
   }

}</source>

Employee charge = 31
Civil Employee charge = 40

Using enum as a member for a struct

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text;

   enum orientation : byte
   {
       north = 1,
       south = 2,
       east = 3,
       west = 4
   }
   struct route
   {
       public orientation direction;
       public double distance;
   }</source>