使用注释将枚举转换为字符串(反之亦然) [英] Converting enum to string (and viceversa) using annotations

查看:193
本文介绍了使用注释将枚举转换为字符串(反之亦然)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我发现自己需要将枚举转换为字符串或反之时,通常会利用描述属性

Usually, when I find myself in need to convert an enum to a string or viceversa, I generally take advantage of the Description Attribute.

例如,如果我有以下枚举:

For instance, If I had the following enum:

public enum QueryOperations
{
     [Description("eq")]
     Equals,

     [Description("gt")]
     GreaterThan,

     [Description("lt")]
     LessThan
}

我会将 QueryOperations.GreaterThan 转换为字符串使用其 DescriptionAttribute 的值,即它将被转换为 gt

I would convert QueryOperations.GreaterThan to a string using its DescriptionAttribute's value, i.e., it would be converted to "gt".

以同样的方式,如果我要将 lt 转换为 QueryOperations ,我最终会得到 QueryOperations.LessThan

In the same way, If i was to convert "lt" to QueryOperations, I would end up with QueryOperations.LessThan.

我真的很喜欢这种方法,而且从未失败过远。我认为它是灵活的,易于理解的,并且与枚举的值名称脱钩。

I really like this approach and never failed me so far. I think it is flexible, easy to understand and it is decoupled from the enum's value names.

但是,引用MSDN的是 DescriptionAttribute

However, quoting MSDN, a DescriptionAttribute:


[...]指定属性或事件的描述。

[...] Specifies a description for a property or event.

显示了一个示例:

[Description("The image associated with the control"),Category("Appearance")] 
public Image MyImage { get; set; }

这使我感到困扰,因为似乎 DescriptionAttribute的目的在语义上与我使用它的用途不同。

This troubles me because it seems that the purpose of the DescriptionAttribute is semantically different to what I use it for.

使用属性转换枚举不是一个愚蠢或疯狂的想法,所以我的问题是:

Using Attributes to convert an enum is not a silly nor crazy idea, so my question is:

是否存在为此情况专门设计的属性?

类似以下内容:

public enum QueryOperations
{
    [StringRepresentation("eq")]
    Equals,
    //...
}


推荐答案

简短的回答是不,没有任何内置内容。

Short answer is no, there's not anything built in.

我认为,如果您提出的用例是您需要做的典型事情,那么您会更好创建自定义属性。 Description 属性 可以按您使用的方式使用,但是正如您已经提到的,它的真正含义是易于理解描述。

I think if the use case you presented is typical of what you need to do, you're better off creating a custom attribute. The Description attribute can be used in the way you're using it, but as you already mentioned, it's really meant to be a human-readable description.

例如,您可以执行以下操作:

For instance, you could do something like this:

    public class StringRepresentationAttribute : Attribute
    {
        public StringRepresentationAttribute(string stringRep)
        {
            this._stringRep = stringRep;
        }

        public string StringRepresentation { get { return _stringRep; } }

        private readonly string _stringRep;

        public override string ToString()
        {
            return StringRepresentation;
        }
    }

然后有类似这样的扩展方法:

Then have something like this as an extension method:

public static string GetStringRepresentation(this Enum en)
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(StringRepresentationAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return ((StringRepresentationAttribute)attrs[0]).StringRepresentation;
                }
            }

            return en.ToString();
        }

您的枚举变为:

public enum QueryOperations
{
     [StringRepresentation("eq")]
     Equals,

     [StringRepresentation("gt")]
     GreaterThan,

     [StringRepresentation("lt")]
     LessThan
}

现在您可以:

string operatorAsString = QueryOperations.LessThan.GetStringRepresentation ();

这篇关于使用注释将枚举转换为字符串(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆