poniedziałek, 23 lutego 2009

enum DisplayText

http://www.west-wind.com/weblog/posts/632732.aspx

I usually don't like to use enum values as display content.
Using a custom DisplayText attribute on the enum value that is
extracted in the UI is IMHO more flexible and less code. :-)

public enum BugStatusTypes
{
[DisplayText(Text = "Entered")]
Entered,
[DisplayText(Text = "In Process")]
InProcess,
Fixed,
ByDesign,
NotReproducible,
NoBug,
None
}


Often times this will save some cross assembly refactorings that would
arise as the display text needs to be changed.

You
can then extract the display text with a simple method. (Making it an
extension methods enables calling it directly off the enum value)
public static string GetDisplayText(this Enum enumValue)
{
var type = enumValue.GetType();
MemberInfo[] memberInfo = type.GetMember(enumValue.ToString());

if (memberInfo == null || memberInfo.Length == 0)
return enumValue.ToString();

object[] attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayTextAttribute), false);
if (attributes == null || attributes.Length == 0)
return enumValue.ToString();

return ((DisplayTextAttribute)attributes[0]).Text;
}


The calling code is dead simple.

string displayValue = BugStatusTypes.Entered.GetDisplayText();



The custom attribute
public class DisplayTextAttribute : Attribute
{
public string Text { get; set; }
}


What do you think?

Brak komentarzy: