web 2.0

Valeurs String avec les Enum en C#

Bonjour !

Il m'est souvent arrivé de devoir faire correspondre des champs de type nvarchar de ma base de données avec des Enums dans mes couches d'accès aux données. Comme tous le monde le sais les Enums sont normalement de type Int.

Exemple :

    public enum Test : int
    {
        MaValeur = 1,
        MaValeur2 = 2
    }

 

Malheureusement lorsque l'ont veut faire correspondre des données String avec un Enum cela se complique ... :(
Cependant comme nous l'explique Stefan Sedich sur son blog une solution existe ! :)

Premièrement il est nécessaire de créer une classe d'attribut personnalisée

    /// <summary>
    /// This attribute is used to represent a string value
    /// for a value in an enum.
    /// </summary>
    public class StringValueAttribute : Attribute
    {

        #region Properties

       
/// <summary>
        /// Holds the stringvalue for a value in an enum.
        /// </summary>
        public string StringValue { get; protected set; }

        #endregion

        #region
Constructor

       
/// <summary>
        /// Constructor used to init a StringValue Attribute
        /// </summary>
        /// <param name="value"></param>
        public StringValueAttribute(string value)
        {
           
this.StringValue = value;
        }

        #endregion
    }

 

Ensuite une petite Extension de méthode afin d'avoir accès à la méthode GetStringValue sur n'importe quelles Enums.

public static class MyExtensions
    {
       
/// <summary>
        /// Will get the string value for a given enums value, this will
        /// only work if you assign the StringValue attribute to
        /// the items in your enum.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetStringValue(this Enum value)
        {
           
// Get the type
            Type type = value.GetType();

           
// Get fieldinfo for this type
            FieldInfo fieldInfo = type.GetField(value.ToString());

           
// Get the stringvalue attributes
            StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
               
typeof(StringValueAttribute), false) as StringValueAttribute[];

           
// Return the first if there was a match.
            return attribs.Length > 0 ? attribs[0].StringValue : null;
        }
    }

 

Il est maintenant simple d'utiliser cet attribut sur nos Enums.

        public enum Test : int
        {
            [
StringValue("a")]
            Foo = 1,
            [
StringValue("b")]
            Something = 2
        }

 

        public void Dummy()
        {
           
Test testEnum = Test.Foo;
           
string val = testEnum.GetStringValue();

           
string val2 = Test.Foo.GetStringValue();
        }

 

Et voila en espérant que cela vous sera utile.

 

Yoann,



Views(1237)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Comments

Technorati Profile