IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Enum, convert et transtypage


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre émérite Avatar de kheironn
    Homme Profil pro
    Chef de projets technique C# / MVC / .Net
    Inscrit en
    Février 2007
    Messages
    822
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Chef de projets technique C# / MVC / .Net
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2007
    Messages : 822
    Par défaut Enum, convert et transtypage
    Bonjour,

    J'ai un enum contenant un certain nombre de valeurs (jusque là, rien d'exceptionnel !)

    Je sais que l'on peut transtyper un int en valeur d'enum
    Mais j'aimerais pouvoir transtyper ou convertir une chaine en valeur d'enum.

    ex :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    enum Week { lun, Mar, etc.}
    Week maVal = (Week)0; (maVal = Lun)
     
    // je cherche à faire (ou avec une convertion )
    Week maVal = (Week)"Lun"; (maVal = Lun)
    Je n'ai rien trouver (ou mal cherché) à ce sujet.

    Une idée ?

    Merci

  2. #2
    Membre éprouvé
    Profil pro
    Inscrit en
    Décembre 2003
    Messages
    97
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2003
    Messages : 97
    Par défaut
    La fonction Enum.Parse fait ce que tu cherches

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Week maval = Enum.Parse(typeof(Week), "lun");
    Ou, si tu veux ignorer les majuscules :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Week maval = Enum.Parse(typeof(Week), "Lun", true);

  3. #3
    Membre émérite Avatar de kheironn
    Homme Profil pro
    Chef de projets technique C# / MVC / .Net
    Inscrit en
    Février 2007
    Messages
    822
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Chef de projets technique C# / MVC / .Net
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2007
    Messages : 822
    Par défaut
    Cool, je ne connaisais pas Enum.parse...

    Merci !

  4. #4
    CUCARACHA
    Invité(e)
    Par défaut Aller, petit cadeau...
    Ca :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
     
    using System;
    using System.Collections;
    using System.Reflection;
    namespace InnovaSites.Objects.CommonLayer
    {
        #region Class StringEnum
     
        /// <summary>
        /// Helper class for working with 'extended' enums using <see cref="StringValueAttribute"/> attributes.
        /// </summary>
        public class StringEnum
        {
            #region Instance implementation
     
            private Type _enumType;
            private static Hashtable _stringValues = new Hashtable();
     
            /// <summary>
            /// Creates a new <see cref="StringEnum"/> instance.
            /// </summary>
            /// <param name="enumType">Enum type.</param>
            public StringEnum(Type enumType)
            {
                if (!enumType.IsEnum)
                    throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", enumType.ToString()));
     
                _enumType = enumType;
            }
     
            /// <summary>
            /// Gets the string value associated with the given enum value.
            /// </summary>
            /// <param name="valueName">Name of the enum value.</param>
            /// <returns>String Value</returns>
            public string GetStringValue(string valueName)
            {
                Enum enumType;
                string stringValue = null;
                try
                {
                    enumType = (Enum)Enum.Parse(_enumType, valueName);
                    stringValue = GetStringValue(enumType);
                }
                catch (Exception) { }//Swallow!
     
                return stringValue;
            }
     
            /// <summary>
            /// Gets the string values associated with the enum.
            /// </summary>
            /// <returns>String value array</returns>
            public Array GetStringValues()
            {
                ArrayList values = new ArrayList();
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in _enumType.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        values.Add(attrs[0].Value);
     
                }
     
                return values.ToArray();
            }
     
            /// <summary>
            /// Gets the values as a 'bindable' list datasource.
            /// </summary>
            /// <returns>IList for data binding</returns>
            public IList GetListValues()
            {
                Type underlyingType = Enum.GetUnderlyingType(_enumType);
                ArrayList values = new ArrayList();
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in _enumType.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        values.Add(new DictionaryEntry(Convert.ChangeType(Enum.Parse(_enumType, fi.Name), underlyingType), attrs[0].Value));
     
                }
     
                return values;
     
            }
     
            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <returns>Existence of the string value</returns>
            public bool IsStringDefined(string stringValue)
            {
                return Parse(_enumType, stringValue) != null;
            }
     
            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Existence of the string value</returns>
            public bool IsStringDefined(string stringValue, bool ignoreCase)
            {
                return Parse(_enumType, stringValue, ignoreCase) != null;
            }
     
            /// <summary>
            /// Gets the underlying enum type for this instance.
            /// </summary>
            /// <value></value>
            public Type EnumType
            {
                get { return _enumType; }
            }
     
            #endregion
     
            #region Static implementation
     
            /// <summary>
            /// Gets a string value for a particular enum value.
            /// </summary>
            /// <param name="value">Value.</param>
            /// <returns>String Value associated via a <see cref="StringValueAttribute"/> attribute, or null if not found.</returns>
            public static string GetStringValue(Enum value)
            {
                string output = null;
                Type type = value.GetType();
     
                if (_stringValues.ContainsKey(value))
                    output = (_stringValues[value] as StringValueAttribute).Value;
                else
                {
                    //Look for our 'StringValueAttribute' in the field's custom attributes
                    FieldInfo fi = type.GetField(value.ToString());
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                    {
                        _stringValues.Add(value, attrs[0]);
                        output = attrs[0].Value;
                    }
     
                }
                return output;
     
            }
     
            /// <summary>
            /// Parses the supplied enum and string value to find an associated enum value (case sensitive).
            /// </summary>
            /// <param name="type">Type.</param>
            /// <param name="stringValue">String value.</param>
            /// <returns>Enum value associated with the string value, or null if not found.</returns>
            public static object Parse(Type type, string stringValue)
            {
                return Parse(type, stringValue, false);
            }
     
            /// <summary>
            /// Parses the supplied enum and string value to find an associated enum value.
            /// </summary>
            /// <param name="type">Type.</param>
            /// <param name="stringValue">String value.</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Enum value associated with the string value, or null if not found.</returns>
            public static object Parse(Type type, string stringValue, bool ignoreCase)
            {
                object output = null;
                string enumStringValue = null;
     
                if (!type.IsEnum)
                    throw new ArgumentException(String.Format("Supplied type must be an Enum.  Type was {0}", type.ToString()));
     
                //Look for our string value associated with fields in this enum
                foreach (FieldInfo fi in type.GetFields())
                {
                    //Check for our custom attribute
                    StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(StringValueAttribute), false) as StringValueAttribute[];
                    if (attrs.Length > 0)
                        enumStringValue = attrs[0].Value;
     
                    //Check for equality then select actual enum value.
                    if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
                    {
                        output = Enum.Parse(type, fi.Name);
                        break;
                    }
                }
     
                return output;
            }
     
            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="enumType">Type of enum</param>
            /// <returns>Existence of the string value</returns>
            public static bool IsStringDefined(Type enumType, string stringValue)
            {
                return Parse(enumType, stringValue) != null;
            }
     
            /// <summary>
            /// Return the existence of the given string value within the enum.
            /// </summary>
            /// <param name="stringValue">String value.</param>
            /// <param name="enumType">Type of enum</param>
            /// <param name="ignoreCase">Denotes whether to conduct a case-insensitive match on the supplied string value</param>
            /// <returns>Existence of the string value</returns>
            public static bool IsStringDefined(Type enumType, string stringValue, bool ignoreCase)
            {
                return Parse(enumType, stringValue, ignoreCase) != null;
            }
     
            #endregion
        }
     
        #endregion
     
        #region Class StringValueAttribute
     
        /// <summary>
        /// Simple attribute class for storing String Values
        /// </summary>
        public class StringValueAttribute : Attribute
        {
            private string _value;
     
            /// <summary>
            /// Creates a new <see cref="StringValueAttribute"/> instance.
            /// </summary>
            /// <param name="value">Value.</param>
            public StringValueAttribute(string value)
            {
                _value = value;
            }
     
            /// <summary>
            /// Gets the value.
            /// </summary>
            /// <value></value>
            public string Value
            {
                get { return _value; }
            }
        }
     
        #endregion
    }
    pis ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
     
            /// <summary>
            /// Exemples d'utilisation:
            /// 
            /// 1. Converttion en int
            /// int iWed = Convert.EnumTypeTo<int>(DayOfWeek.Wednesday);
            /// 
            /// 2. Convertion en string
            /// 
            /// string sWed = Convert.EnumTypeTo<string>(DayOfWeek.Wednesday);
            /// 
            /// conversion de la valeur vers l'enum
            /// 
            /// DayOfWeek wednesday = Convert.EnumTypeTo<DayOfWeek>(sWed);
            /// DayOfWeek wednesday = Convert.EnumTypeTo<DayOfWeek>(iWed);
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="value"></param>
            /// <returns></returns>
            public static T EnumTypeTo<T>(object value)
            {
                Type conversionType = typeof(T);
     
                if (!conversionType.IsGenericType && conversionType.IsEnum)
                {
                    try
                    {
                        if (value.GetType().IsValueType)
                        {
                            return (T)Enum.ToObject(conversionType, value);
                        }
                        else
                        {
                            return (T)Enum.Parse(conversionType, value.ToString());
                        }
                    }
                    catch
                    {
                        return default(T);
                    }
                }
     
                try
                {
                    return (T)Convert.ChangeType(value, conversionType);
                }
                catch
                {
                    return default(T);
                }
            }
    ça permet ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
            public enum enDynamicFormFieldControlTypes
            {
                [StringValue("")]
                _notSet = 0,
                [StringValue("TextBox")]
                TextBox = 1,
                [StringValue("DropDownList")]
                DropDownList = 2,
                [StringValue("TextArea")]
                TextArea = 3,
                [StringValue("Password")]
                Password = 4,
                [StringValue("CheckBoxList")]
                CheckBoxList = 5
            }
    et ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
            public DynamicForm_Field_ControlType(enDynamicFormFieldControlTypes controlType)
            {
                this.Id = Tools.EnumTypeTo<int>(controlType);
                this.Name = StringEnum.GetStringValue(controlType);
            }
            public enDynamicFormFieldControlTypes toDynamicFormFieldControlTypes
            {
                get
                {
                    return Tools.EnumTypeTo<enDynamicFormFieldControlTypes>(this.Id);
                }
            }
    ou encore ça:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    string toto = StringEnum.GetStringValue(enDynamicFormFieldControlTypes.CheckBoxList)
    et plein d'autres chose que je te laisse le plaisir de découvrir...

    ++

    Laurent Jordi

  5. #5
    Membre émérite Avatar de kheironn
    Homme Profil pro
    Chef de projets technique C# / MVC / .Net
    Inscrit en
    Février 2007
    Messages
    822
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Pyrénées Atlantiques (Aquitaine)

    Informations professionnelles :
    Activité : Chef de projets technique C# / MVC / .Net
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2007
    Messages : 822
    Par défaut
    Merci Laurent.

    Maintenant, j'en viens à me poser une question sur la pertinance de mes traitements

    Je fais :
    • Lecture d'un XML dont l'un des champs contient le nom d'une propriété d'un objet et la nouvelle valeur sachant que d'autres propriétés seront affectées en fonction de la première, ou pas...1
    • transforamtion en valeur d'enum de la propriété lue
    • passage de l'enum comme paramètre
    • traitement final : si l'enum a certaines valeurs, alors je modifie certains objets (instance) avec les traitements en cascade, sinon, je modifie la propriétés seule.


    Au final, je pense que passer un PropertyInfo serait mieux et dans ma methode principale, je teste certaines valeurs et j'agis en conséquence.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Enum en parametre d'un converter
    Par scapefrom dans le forum Windows Presentation Foundation
    Réponses: 6
    Dernier message: 09/09/2009, 13h13
  2. [SQL Server] Error converting data type varchar...
    Par Sir Tengu dans le forum MS SQL Server
    Réponses: 9
    Dernier message: 13/06/2003, 10h46
  3. [Debutant] [Date] convertion date
    Par BenoitM dans le forum Collection et Stream
    Réponses: 4
    Dernier message: 17/04/2003, 14h55
  4. Convertion de type VARIANT à type CString
    Par j_grue dans le forum MFC
    Réponses: 2
    Dernier message: 07/11/2002, 14h18
  5. [transtypage]PChar et WideString
    Par rbag dans le forum Bases de données
    Réponses: 2
    Dernier message: 05/09/2002, 20h12

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo