devstory

Le Tutoriel de C# Enum

  1. Qu'est-ce que C# Enum ?
  2. Possibilité d'utiliser l'opérateur == pour comparer les éléments de enum
  3. Parcourir les éléments de Enum
  4. Enum et Attribute
  5. Peut-Enum avoir des méthodes ou non ?

1. Qu'est-ce que C# Enum ?

Enum en C# est un mot-clé, il est utilisé pour déclarer une énumération (enumeration).
Maintenant, nous devons voir s'il n'y a pas un Enum dans certaines situations que vous devrez faire comment, par exemple vous avez besoin d'une liste contenant les jours de la semaine. En général, vous définissez les sept constantes pour représenter 7 jours de la semaines.
WeekDayConstants.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    class WeekDayConstants
    {
         public const int MONDAY = 2;
         public const int TUESDAY = 3;
         public const int WEDNESDAY = 4;
         public const int THURSDAY = 5;

         public const int FRIDAY = 6;
         public const int SATURDAY = 7;
         public const int SUNDAY = 1;
    }
}
Une classe avec une méthode renvoie le travail à faire chaque jour précis de la semaine (Similaire au calendrier)
Timetable.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    class Timetable
    {
        // Returns name of Job will do
        public static String getJob(int dayInWeek)
        {
            if (dayInWeek == WeekDayConstants.SATURDAY
                    || dayInWeek == WeekDayConstants.SUNDAY)
            {
                return "Nothing";
            }
            return "Coding";
        }
    }
}
Il est évidemment que le code n'est pas de sûre. Par exemple, lorsque vous appelez la fonction Timetable.getJob (int) mais le paramètre d'entrée n'appartient pas à l'ensemble de la valeur définie
  • No Type-Safety : Tout d'abord, vous trouvez que votre code n'est pas en sécurité, vous pouvez appeler la méthode GetJob(int) et l'attribuer une valeur
  • No Meaningful Printing : Si vous voulez imprimer les jours de la semaine ce sera les chiffres, au lieu d'un mot significatif comme "MONDAY"
Et voici la méthode d'utilisation Enum pour définir les jours de la semaine.
WeekDay.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    public enum WeekDay
    {
       MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }
}
Et l'exemple d'utilisation enum WeekDay:
Timetable2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    class Timetable2
    {
        public static String getJob(WeekDay weekDay)
        {
            if (weekDay == WeekDay.SATURDAY || weekDay == WeekDay.SUNDAY)
            {
                return "Nothing";
            }
            return "Coding";
        }
    }
}

2. Possibilité d'utiliser l'opérateur == pour comparer les éléments de enum

Enum est un objet de référence comme une classe, une interface, mais il peut également être utilisé pour comparer ==.
Vooyez comment les objets de référence (objet de référence) sont comparés :
// To compare the reference object, generally used method equals(..)
object obj1 = ...;

// Comparing object with null, can use the == operator
if (obj1 == null)
{

}

object obj2 = ...;
// Not null
if (obj1 != null)
{
    // Comparing two objects.
    if (obj1.Equals(obj2))
    {

    }
}
Avec Enum, vous pouvez utiliser l'opérateur == pour faire la comparaison.
CompareEnumDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
   class CompareEnumDemo
   {
       public static void Main(string[] args)
       {
           WeekDay today = WeekDay.SUNDAY;
           // Use the == operator to compare two elements of Enum
           if (today == WeekDay.SUNDAY)
           {
               Console.WriteLine("Today is Sunday");
           }
           Console.Read();
       }
   }
}

3. Parcourir les éléments de Enum

Nous pouvons parcourir sur tous les éléments de Enum. Voyez l'exemple d'illustration.
ValuesDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    class ValuesDemo
    {
        public static void Main(string[] args)
        {
            // Get all the elements of the Enum.
            Array allDays = Enum.GetValues(typeof(WeekDay));
            foreach (WeekDay day in allDays)
            {
                Console.WriteLine("Day: " + day);
            }
            Console.Read();
        }   
    }
}
Les résultats de l'exécution de l'exemple :
Day: MONDAY
Day: TUESDAY
Day: WEDNESDAY
Day: THURSDAY
Day: FRIDAY
Day: SATURDAY
Day: SUNDAY

4. Enum et Attribute

Vous pouvez joindre des Attribute aux éléments de Enum, cela aide Enum à apporter plus d'informations et vous pouvez récupérer les informations correspondant à chaque élément de Enum.

Voyez plus :
  • Hướng dẫn và ví dụ C# Attribute
GenderAttr.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    class GenderAttr : Attribute
    {
        // code: M, text = Male
        // code: F, text = Female
        internal GenderAttr(string code, string text)
        {
            this.Code = code;
            this.Text = text;
        }
        public string Code { get; private set; }
        public string Text { get; private set; }  
    }
}
enum Gender (Sexe) 2 éléments MALE (mâle) et FEMALE (femelle).
Gender.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
    public enum Gender
    {
        // A element of Enum, has attribute
        [GenderAttr("M","Male")]
        MALE,
        // A element of Enum, has attribute
        [GenderAttr("F","Female")]
        FEMALE
    }
}
Genders.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace CSharpEnumTutorial
{
    class Genders
    {
        // Returns Gender corresponding to the code.
        // (This method may returns null)
        public static Gender? GetGenderByCode(string code)
        {
            // Get all the elements of the Enum.
            Array allGenders = Enum.GetValues(typeof(Gender));

            foreach (Gender gender in allGenders)
            {
                string c = GetCode(gender);
                if (c == code)
                {
                    return gender;
                }
            }
            return null;
        }
        public static string GetText(Gender gender)
        {
            GenderAttr genderAttr = GetAttr(gender);
            return genderAttr.Text;
        }
        public static string GetCode(Gender gender)
        {
            GenderAttr genderAttr = GetAttr(gender);
            return genderAttr.Code;
        }
        private static GenderAttr GetAttr(Gender gender)
        {
            MemberInfo memberInfo = GetMemberInfo(gender);
            return (GenderAttr)Attribute.GetCustomAttribute(memberInfo, typeof(GenderAttr));
        }
        private static MemberInfo GetMemberInfo(Gender gender)
        {
            MemberInfo memberInfo
                = typeof(Gender).GetField(Enum.GetName(typeof(Gender), gender));

            return memberInfo;
        }
    }
}
Et l'exemple de l'utilisation enum Gender:
GenderTest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
   class GenderTest
   {
       public static void Main(string[] args)
       {
           Gender marryGender = Gender.FEMALE;
           Console.WriteLine("marryGender: " + marryGender);
           Console.WriteLine("Code: " + Genders.GetCode(marryGender)); // F
           Console.WriteLine("Text: " + Genders.GetText(marryGender)); // Femate
           String code = "M";
           Console.WriteLine("Code: " + code);
           // Phương thức có thể trả về null.
           Gender? gender = Genders.GetGenderByCode(code);
           Console.WriteLine("Gender by code: " + gender);
           Console.Read();
       }
   }
}
Exécutez l'exemple :
marryGender: FEMALE
Code: F
Text: Female
Code: M
Gender by code: MALE

5. Peut-Enum avoir des méthodes ou non ?

En C# Enum ne peut pas contenir des méthodes, mais si vous voulez posséder quelque chose comme Enum et avoir les méthodes que vous pouvez définir une classe, cette classe ne permet pas de créer des objets en dehors les objets qu'ils ont été mis à la disposition.
GenderX.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpEnumTutorial
{
   class GenderX
   {
       public static readonly GenderX MALE = new GenderX("M","Male");
       public static readonly GenderX FEMALE = new GenderX("F","Female");
       private string code;
       private string text;

       // Private Constructor: Do not allow creating objects from outside class.
       private GenderX(string code, string text)
       {
           this.code = code;
           this.text = text;
       }
       public string GetCode()
       {
           return this.code;
       }
       public string GetText()
       {
           return this.text;
       }
       public static GenderX GetGenderByCode(string code)
       {
           if (MALE.code.Equals(code))
           {
               return MALE;
           }
           else if (FEMALE.code.Equals(code))
           {
               return FEMALE;
           }
           return null;
       }
   }
}