1

我想保留组合框的当前选定值并在以后恢复它。为了管理组合框中的值,我有一个带有描述属性的枚举类型。description 属性在运行时成为组合框字符串值(其中之一),并且与其关联的枚举常量在内部用于编程目的。我从以下 Stack Overflow 帖子中获得了这项技术:

c#:如何使用枚举来存储字符串常量?

该帖子包含此博客帖子的评论之一中的链接:

http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx

执行枚举到字符串转换魔术的 GetDescription() 方法从该帖子复制到此处,并在参数列表中添加了“this”关键字,因此我可以将其用作枚举类型的扩展方法:

    public static string GetDescription(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(DescriptionAttribute), false);

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

        // Unable to find a description attribute for the enum.  Just return the
        //  value of the ToString() method.
        return en.ToString();
    }

所以我已经完全充实了等式的一侧,并且效果很好。现在我想走另一条路。我想创建一个方法,该方法采用字符串并通过遍历特定枚举类型的描述属性并返回与匹配字符串的描述属性关联的枚举值来返回正确的枚举值。一个假设的方法声明将是:

public static Enum GetEnumValue(string str){}

然而,该声明的一个直接问题是它不返回特定的枚举类型。我不确定如何正确声明和强制转换,以便返回正确的枚举类型。是否可以为 GetDescription() 方法创建这种补充方法,如果可以,我如何制作它以便它适用于任何特定的枚举类型?如果我能做到这一点,我将有一个方便的解决方案来解决在用于持久控制设置的字符串之间进行转换然后在以后恢复它们的常见问题,所有这些都由枚举支持。

4

1 回答 1

3

您缺少一条信息,即要查看的 Enum 信息。

目前您只传入一个字符串,而不是 Enum 的类型。

最简单的方法是使用泛型函数

请注意,此内容是即兴的,甚至可能无法编译。

public static TEnum GetEnumValue<TEnum>(string str)
    where TEnum : struct //enum is not valid here, unfortunately
{
    foreach (MemberInfo memInfo in typeof(TEnum).GetMembers())
    {
        object[] attrs = memInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attrs != null && attrs.Length > 0)
        {
            if (((DescriptionAttribute)attrs[0]).Description == str)
            {
                return (TEnum)(object)Enum.Parse(typeof(TEnum),memInfo.Name);
            }
        }
    }

    // Unable to find a description attribute for the enum.
    return (TEnum)(object)Enum.Parse(typeof(TEnum),str);
}

Then you can use typeof(TEnum) to get the type object for the requested enumeration and do your logic.

Finally you can cast back to TEnum before returning, saving yourself the work on the calling side.

EDIT:

Added a rough example, untested.

于 2013-02-07T18:21:28.063 回答