HAVIT Knowledge Base

Vývoj webových aplikací, .NET, SQL, návrh
Welcome to HAVIT Knowledge Base Sign in | Join | Help
-
Home Články Forums Obrázky Soubory

.NET Framework

Microsoft .NET Framework, Base Class Library

Vlastní textová reprezentace výčtového typu enum - alternativa ToString()

K výčtovému typu enum nelze konvenčními metodami udělat vlastní textovou reprezentaci, není jak overridovat metodu ToString(). Pokud chceme každé hodnotě přiřadit pouze jedinou "user-friendly" textovou reprezentaci, můžeme využít atributu DescriptionAttribute:

public enum StavZakazky
{
    [Description("Nedefinován")]
    Nedefinovan,

    [Description("Vytištěno")]
    TiskHotovo
}

public static class EnumExt
{
    public static string GetDescription(Type enumType, object hodnota)
    {
        string strRet = "<na>";
        try
        {
            System.Reflection.FieldInfo objInfo = enumType.GetField(Enum.GetName(enumType, hodnota));

            System.ComponentModel.DescriptionAttribute objDescription =
                (System.ComponentModel.DescriptionAttribute)objInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true)[0];

            strRet = objDescription.Description;
        }
        catch(Exception)
        {
            // chybí description
        }
        return strRet;
    }
}
Interní: Implementováno jako Havit.EnumExt.GetDescription().

Published 13. prosince 2006 14:48 by Robert Haken
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

What do you think?

(required) 
(optional)
(required) 
Enter the code you see below

Submit