Csharp/C Sharp/Data Types/Enum

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

A public enum in one class from another class

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// // Enum.cs - Demonstrates using a public enum in one class from // another class // // Compile this program with the following command line: // C:>csc enum.cs // namespace nsEnum {

   using System;
   public class Enum
   {

// Define the enum type

       public enum Weekdays
       {
               Sun, Mon, Tues, Wed, Thurs, Fri, Sat, Count
       }
       static public void Main ()
       {
           clsSecond second = new clsSecond();
           second.ShowEnum ();
       }
   }
   class clsSecond
   {
       public void ShowEnum()
       {

// Use the class name with the enum name

           Console.WriteLine ("Tuesday is day {0} in the week",
                               (int) Enum.Weekdays.Tues);
       }
   }

}


      </source>


Demonstrate an enumeration

<source lang="csharp">

using System;

public class EnumDemo {

 enum apple { Jonathan, GoldenDel, RedDel, Winsap, 
              Cortland, McIntosh }; 

 public static void Main() { 
   string[] color = { 
     "Red", 
     "Yellow", 
     "Red", 
     "Red", 
     "Red", 
     "Redish Green" 
   }; 

   apple i; 

   for(i = apple.Jonathan; i <= apple.McIntosh; i++)  
     Console.WriteLine(i + " has value of " + (int)i); 

   Console.WriteLine(); 

   for(i = apple.Jonathan; i <= apple.McIntosh; i++)  
     Console.WriteLine("Color of " + i + " is " + 
                        color[(int)i]); 

 } 

}


      </source>


Demonstrate an enumerator

<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852

  • /

// Demonstrate an enumerator.

using System; using System.Collections;

public class EnumeratorDemo {

 public static void Main() { 
   ArrayList list = new ArrayList(1); 

   for(int i=0; i < 10; i++) 
     list.Add(i); 

   // Use enumerator to access list. 
   IEnumerator etr = list.GetEnumerator(); 
   while(etr.MoveNext())  
     Console.Write(etr.Current + " "); 

   Console.WriteLine(); 

   // Re-enumerate the list. 
   etr.Reset(); 
   while(etr.MoveNext())  
     Console.Write(etr.Current + " "); 

   Console.WriteLine(); 
 } 

}


      </source>


Demonstrate IDictionaryEnumerator

<source lang="csharp"> /* C#: The Complete Reference by Herbert Schildt Publisher: Osborne/McGraw-Hill (March 8, 2002) ISBN: 0072134852

  • /

// Demonstrate IDictionaryEnumerator.

using System; using System.Collections;

public class IDicEnumDemo {

 public static void Main() { 
   // Create a hash table. 
   Hashtable ht = new Hashtable(); 
    
   // Add elements to the table 
   ht.Add("Tom", "555-3456"); 
   ht.Add("Mary", "555-9876"); 
   ht.Add("Todd", "555-3452"); 
   ht.Add("Ken", "555-7756"); 

   // Demonstrate enumerator 
   IDictionaryEnumerator etr = ht.GetEnumerator(); 
   Console.WriteLine("Display info using through Entry."); 
   while(etr.MoveNext())  
    Console.WriteLine(etr.Entry.Key + ": " +  
                      etr.Entry.Value); 

   Console.WriteLine(); 

   Console.WriteLine("Display info using Key and Value directly."); 
   etr.Reset(); 
   while(etr.MoveNext())  
    Console.WriteLine(etr.Key + ": " +  
                      etr.Value); 
    
 } 

}


      </source>


Enum by IEnumerable

<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765

  • /
using System;
namespace Enumeration
{
    using System;
    using System.Collections;
    // implements IEnumerable
    class ListBoxTest : IEnumerable
    {
        private string[] strings;
        private int ctr = 0;
        // private nested implementation of ListBoxEnumerator
        private class ListBoxEnumerator : IEnumerator
        {
            // member fields of the nested ListBoxEnumerator class
            private ListBoxTest currentListBox;
            private int index;
            // public within the private implementation
            // thus, private within ListBoxTest
            public ListBoxEnumerator(ListBoxTest currentListBox)
            {
                // a particular ListBoxTest instance is
                // passed in, hold a reference to it
                // in the member variable currentListBox.
                this.currentListBox = currentListBox;
                index = -1;
            }
            // Increment the index and make sure the
            // value is valid
            public bool MoveNext()
            {
                index++;
                if (index >= currentListBox.strings.Length)
                    return false;
                else
                    return true;
            }
            public void Reset()
            {
                index = -1;
            }
            // Current property defined as the
            // last string added to the listbox
            public object Current
            {
                get
                {
                    return(currentListBox[index]);
                }
            }
        }  // end nested class
        // Enumerable classes can return an enumerator
        public IEnumerator GetEnumerator()
        {
            return (IEnumerator) new ListBoxEnumerator(this);
        }
        // initialize the listbox with strings
        public ListBoxTest(params string[] initialStrings)
        {
            // allocate space for the strings
            strings = new String[8];
            // copy the strings passed in to the constructor
            foreach (string s in initialStrings)
            {
                strings[ctr++] = s;
            }
        }
        // add a single string to the end of the listbox
        public void Add(string theString)
        {
            strings[ctr] = theString;
            ctr++;
        }
        // allow array-like access
        public string this[int index]
        {
            get
            {
                if (index < 0 || index >= strings.Length)
                {
                    // handle bad index
                }
                return strings[index];
            }
            set
            {
                strings[index] = value;
            }
        }
        // publish how many strings you hold
        public int GetNumEntries()
        {
            return ctr;
        }
    }
   public class EnumerationTester
   {
      public void Run()
      {
          // create a new listbox and initialize
          ListBoxTest currentListBox =
              new ListBoxTest("Hello", "World");
          // add a few strings
          currentListBox.Add("Who");
          currentListBox.Add("Is");
          currentListBox.Add("John");
          currentListBox.Add("Galt");
          // test the access
          string subst = "Universe";
          currentListBox[1] = subst;
          // access all the strings
          foreach (string s in currentListBox)
          {
              Console.WriteLine("Value: {0}", s);
          }
      }
      [STAThread]
      static void Main()
      {
         EnumerationTester t = new EnumerationTester();
         t.Run();
      }
   }
}
          
      </source>


Enum data type comparison

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType Joe = EmpType.VP;
       EmpType Fran = EmpType.Grunt;
       if (Joe < Fran)
           Console.WriteLine("Joe"s value is less than Fran"s value.");
       else
           Console.WriteLine("Fran"s value is less than Joe"s value.");
   }

}

</source>


Enum declare and use it

<source lang="csharp"> /*

* C# Programmers Pocket Consultant
* Author: Gregory S. MacBeth
* Email: gmacbeth@comporium.net
* Create Date: June 27, 2003
* Last Modified Date:
*/

using System; namespace Client.Chapter_3___Structs__Enums__Arrays_and_Classes {

 enum DaysOfWeek
 {
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
 }
 public class EnumsChapter_3___Structs__Enums__Arrays_and_Classes
 {
   static void Main(string[] args)
   {
     DaysOfWeek Today = DaysOfWeek.Monday;
     Console.WriteLine(Today);
   }
 }

}

      </source>


Enumeration Base Types

<source lang="csharp"> enum SmallEnum : byte {

   A,
   B,
   C,
   D

}

      </source>


Enumerations:Bit Flag Enums 1

<source lang="csharp"> using System; [Flags] public enum BitValues: uint {

   NoBits = 0,
   Bit1 = 0x00000001,
   Bit2 = 0x00000002,
   Bit3 = 0x00000004,
   Bit4 = 0x00000008,
   Bit5 = 0x00000010,
   AllBits = 0xFFFFFFFF

} public class BitFlagEnums {

   public static void Member(BitValues value)
   {
       // do some processing here
   }
   public static void Main()
   {
       Member(BitValues.Bit1 | BitValues.Bit2);
   }

}

      </source>


Enumerations:Bit Flag Enums 2

<source lang="csharp"> enum Values {

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

} public class EnumerationsConversions {

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

}

      </source>


Enumerations:Initialization

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

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

} public class EnumerationsInitialization2 {

   public static void Member(Values value)
   {
       // do some processing here
   }
   public static void Main()
   {
       Values value = 0;
       Member(value);
   }

}

      </source>


Enumerations Initialization 2

<source lang="csharp"> enum Values {

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

}

      </source>


Enumerations:The System.Enum Type

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

   red,
   green,
   yellow

} public class TheSystemEnumType1 {

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

}

      </source>


Enumerations: The System.Enum Type 2

<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3

  • /

// 20 - Enumerations\The System.Enum Type // copyright 2000 Eric Gunnerson using System; enum Color {

   red,
   green,
   yellow

} public class TheSystemEnumType2 {

   public static void Main()
   {
       Color c = Color.red;
       
       // enum values and names
       foreach (int i in Enum.GetValues(c.GetType()))
       {
           Console.WriteLine("Value: {0} ({1})", i, Enum.GetName(c.GetType(), i));
       }
       
       // or just the names
       foreach (string s in Enum.GetNames(c.GetType()))
       {
           Console.WriteLine("Name: {0}", s);
       }
       
       // enum value from a string, ignore case
       c = (Color) Enum.Parse(typeof(Color), "Red", true);
       Console.WriteLine("string value is: {0}", c);
       
       // see if a specific value is a defined enum member
       bool defined = Enum.IsDefined(typeof(Color), 5);
       Console.WriteLine("5 is a defined value for Color: {0}", defined);    
   }

}

      </source>


Enumerators and Foreach

<source lang="csharp"> /* A Programmer"s Introduction to C# (Second Edition) by Eric Gunnerson Publisher: Apress L.P. ISBN: 1-893115-62-3

  • /

// 19 - Indexers and Enumerators\Enumerators and Foreach // copyright 2000 Eric Gunnerson using System; using System.Collections; // Note: This class is not thread-safe class IntList: IEnumerable {

   int[] values = new int[10];
   int allocated = 10;
   int count = 0;
   int revision = 0;
   
   public void Add(int value)
   {
       // reallocate if necessary
       if (count + 1 == allocated)
       {
           int[] newValues = new int[allocated * 2];
           for (int index = 0; index < count; index++)
           {
               newValues[index] = values[index];
           }
           allocated *= 2;
       }        
       values[count] = value;
       count++;
       revision++;
   }
   
   public int Count
   {
       get
       {
           return(count);
       }
   }
   
   void CheckIndex(int index)
   {
       if (index >= count)
       throw new ArgumentOutOfRangeException("Index value out of range");
   }
   
   public int this[int index]
   {
       get
       {
           CheckIndex(index);
           return(values[index]);
       }
       set
       {
           CheckIndex(index);
           values[index] = value;
           revision++;
       }
   }
   
   public IEnumerator GetEnumerator()
   {
       return(new IntListEnumerator(this));
   }
   
   internal int Revision
   {
       get
       {
           return(revision);
       }
   }

} class IntListEnumerator: IEnumerator {

   IntList    intList;
   int revision;
   int index;
   
   internal IntListEnumerator(IntList intList)
   {
       this.intList = intList;
       Reset();
   }
   
   public bool MoveNext()
   {
       index++;
       if (index >= intList.Count)
       return(false);
       else
       return(true);
   }
   
   public object Current
   {
       get
       {
           if (revision != intList.Revision)
           throw new InvalidOperationException("Collection modified while enumerating.");
           return(intList[index]);
       }
   }
   
   public void Reset()
   {
       index = -1;
       revision = intList.Revision;
   }

} public class EnumeratorsandForeach {

   public static void Main()
   {
       IntList list = new IntList();
       
       list.Add(1);
       list.Add(55);
       list.Add(43);
       
       foreach (int value in list)
       {
           Console.WriteLine("Value = {0}", value);
       }
       
       foreach (int value in list)
       {
           Console.WriteLine("Value = {0}", value);
           list.Add(124);
       }
   }

}

      </source>


Enum.Format()

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       Console.WriteLine("You are a {0}", fred.ToString());
       Console.WriteLine("Hex value is {0}", Enum.Format(typeof(EmpType), fred, "x"));
       Console.WriteLine("Int value is {0}", Enum.Format(typeof(EmpType), fred, "D"));
   }

}

</source>


Enum.IsDefined()

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       // Does EmpType have a SaleEmployee value?
       if (Enum.IsDefined(typeof(EmpType), "SalesEmployee"))
           Console.WriteLine("Yep, we have sales people.");
       else
           Console.WriteLine("No, we have no profits....");
   }

}

</source>


Enum Parse

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       EmpType sally = (EmpType)Enum.Parse(typeof(EmpType), "Manager");
       Console.WriteLine("Sally is a {0}", sally.ToString());
   }

}

</source>


Enum Values

<source lang="csharp"> /* Learning C# by Jesse Liberty Publisher: O"Reilly ISBN: 0596003765

  • /

public class EnumValues

{
   // declare the enumeration
   enum Temperatures
   {
      WickedCold = 0,
      FreezingPoint = 32,
      LightJacketWeather = 60,
      SwimmingWeather = 72,
      BoilingPoint = 212,
   }
   static void Main( )
   {
      System.Console.WriteLine("Freezing point of water: {0}",
         (int) Temperatures.FreezingPoint );
      System.Console.WriteLine("Boiling point of water: {0}",
         (int) Temperatures.BoilingPoint );
   }
}
          
      </source>


Get all stats for EmpType.

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       Array obj = Enum.GetValues(typeof(EmpType));
       Console.WriteLine("This enum has {0} members:", obj.Length);
   }

}

</source>


Get Enum"s type, hex and value.

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       Console.WriteLine("You are a {0}", fred.ToString());
       Console.WriteLine("Hex value is {0}", Enum.Format(typeof(EmpType), fred, "x"));
       Console.WriteLine("Int value is {0}", Enum.Format(typeof(EmpType), fred, "D"));
   }

}

</source>


Get underlying type

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       Console.WriteLine(Enum.GetUnderlyingType(typeof(EmpType)));
   }

}

</source>


how a derived class may override an existing enumeration in a base class

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// // BaseEnum.cs - Demonstrates how a derived class may override an existing // enumeration in a base class // // Compile this program with the following command line: // C:>csc baseenum.cs // namespace nsEnum {

   using System;
   public class clsBaseClass
   {

// Define the enum type

       public enum Weekdays
       {
               Sun, Mon, Tues, Wed, Thurs, Fri, Sat
       }
       static public void Main ()
       {
           Console.WriteLine ("In base class, Sunday = " +
                              (int) Weekdays.Sun);
           clsNewClass second = new clsNewClass();
           second.ShowEnum ();
       }
   }
   class clsNewClass : clsBaseClass
   {
       public new enum Weekdays
       {
               Sun = 1, Mon, Tues, Wed, Thurs, Fri, Sat
       }
       public void ShowEnum()
       {

// Use the class name with the enum name

           Console.WriteLine ("In derived class, Sunday = " +
                              (int) Weekdays.Sun);
       }
   }

}

      </source>


Illustrates the use of an enumeration that defines the orbital periods of the first four planets in days

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example2_11.cs illustrates the use of an enumeration
 that defines the orbital periods of the first four
 planets in days
  • /

public class Example2_111 {

 enum PlanetPeriods
 {
   Mercury = 88,
   Venus = 225,
   Earth = 365,
   Mars = 687
 }
 public static void Main()
 {
   System.Console.WriteLine("Orbital period for Mars = " +
     (int) PlanetPeriods.Mars + " days");
 }

}


      </source>


Illustrates the use of an enumeration that defines the orbital periods of the first four planets in days, using a base type of long

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example2_12.cs illustrates the use of an enumeration
 that defines the orbital periods of the first four
 planets in days, using a base type of long
  • /

public class Example2_121 {

 enum PlanetPeriods :long
 {
   Mercury = 88,
   Venus = 225,
   Earth = 365,
   Mars = 687
 }
 public static void Main()
 {
   System.Console.WriteLine("Orbital period for Mars = " +
     (long) PlanetPeriods.Mars + " days");
 }

}

      </source>


switch statement with Enum and call its ToString function

<source lang="csharp"> using System; enum EmpType : byte {

   Manager = 10,
   Grunt = 1,
   Contractor = 100,
   VP = 9

} class Program {

   public static void AskForBonus(EmpType e) {
       switch (e) {
           case EmpType.Contractor:
               Console.WriteLine("1");
               break;
           case EmpType.Grunt:
               Console.WriteLine("2");
               break;
           case EmpType.Manager:
               Console.WriteLine("3");
               break;
           case EmpType.VP:
               Console.WriteLine("4");
               break;
           default: break;
       }
   }
   static void Main(string[] args) {
       EmpType fred;
       fred = EmpType.VP;
       AskForBonus(fred);
       Console.WriteLine(fred.ToString());
   }

}

</source>


The use of an enumeration that defines the positions of the planets in the solar system relative to the Sun

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example2_10.cs illustrates the use of an enumeration
 that defines the positions of the planets in
 the solar system relative to the Sun
  • /

public class Example2_10 {

 enum Planets
 {
   Mercury = 1,
   Venus,
   Earth,
   Mars,
   Jupiter,
   Saturn,
   Uranus,
   Neptune,
   Pluto
 }
 public static void Main()
 {
   System.Console.WriteLine("Position of Earth = " +
     (int) Planets.Earth);
   System.Console.WriteLine("Planets.Earth = " +
     Planets.Earth);
 }

}


      </source>