开发者

Multiple description attributes on emums

C# 4.0

If i want to set description for enum i may use DescriptionAttribute form System.ComponentModel;

public enum EnumWithDescription
{
    [Description("EnumDescription1")]
    EE = 1,
    [Desc开发者_开发技巧ription("EnumDescription2")]
    PP
}

but if i need another specific description i may implement my specific attribute and extension method which will return this additional description. e.g:

public enum EnumWithDescription
{

    [MyDescritption("MyDescription1")]
    [Description("EnumDescription1")]
    EE = 1
}

anumValue.MyExtensionMethod(); // return me MyDescritpion stirng value

may be there is some another more simple ways of doing this?


You may extend DescriptionAttribute like this:

class ExtraDescriptionAttribute : DescriptionAttribute
    {
        private string extraInfo;
        public string ExtraInfo { get { return extraInfo; } set { extraInfo = value; } }

        public ExtraDescriptionAttribute(string description)
        {
            this.DescriptionValue = description;
            this.extraInfo = "";
        }
    }


Not using DescriptionAttribute, as it has AllowMultiple set to false. However, you could always make your attribute allow multiple values - or if you have two types of description to set, you could create an attribute which encapsulates both of these.

To be honest, it's hard to see quite how much easier it could be than the code you've presented. You could have an extension method which specifies which attribute to retrieve, of course (I've started writing one of these for Unconstrained Melody) but beyond that, it looks like you're doing reasonably well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜