Visualizzazione dei risultati da 1 a 3 su 3
  1. #1
    Utente di HTML.it
    Registrato dal
    Nov 2008
    Messaggi
    39

    [c#] Conversione di una stringa in valore enumeratore

    Ho il seguente enumeratore i cui valori sono ripresi in un campo di un database

    codice:
        public enum SwitchField
        {
            UNDEFINED,
            EF,
            HIDE,
            GENERIC,
            SELECT,
            OPTION,
            REQUEST,
            TEXTAREA,
            CURRENCY,
            INTEGER,
            PROG
        }
    Quando vado a leggere i valori dal database ottengo una stringa che non riesco a convertire in un valore dell'enumeratore; ho quindi creato il seguente ciclo per convertire la stringa nell'enumeratore:

    codice:
        string strSwitchField = valoreOttenutoDalDatabase;
        SwitchField switchField;
    
        foreach (int sf in Enum.GetValues(typeof(SwitchField)))
        {
            if (strSwitchField == Enum.GetName(typeof(SwitchField),sf))
            {
                switchField = (SwitchField)Enum.ToObject(typeof(SwitchField),sf);
            }
        }
    Il codice sembra funzionare correttamente, l'unica anomalia è che, nel caso in cui la variabile 'strSwitchField' è uguale a una stringa vuota, la variabile switchField assume il primo valore dell'enumeratore.

    Secondo voi il procedimento è corretto oppure ci sono altri sistemi più efficienti per raggiungere lo stesso risultato?

  2. #2
    I don’t know why I didn’t do this long ago, but I am done writing this:
    codice:
    var val = (SomeEnum)Enum.Parse(typeof(SomeEnum),”someString”);
    I have typed this too many times and it annoys me.

    I wrote a small extension method on the string type to make this better:
    codice:
    public static class StringExtensions
    {
        public static T ToEnum<T>(this string @string)
        {
            return (T)Enum.Parse(typeof (T), @string);
        }
    }
    With this I can now write the previous line as:

    codice:
    var val = "someString".ToEnum<SomeEnum>()
    It is a bit shorter and I think much more readable

    Spero sia utile. Ciao!

  3. #3
    Utente di HTML.it
    Registrato dal
    Nov 2008
    Messaggi
    39
    Molto utile grazie. Ho rivisto il codice e ho dato un'occhiata anche agli extension method che sembrano essere molto utili.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2026 vBulletin Solutions, Inc. All rights reserved.