首页 > 后端开发 > C++ > 如何从其描述属性中获取枚举值?

如何从其描述属性中获取枚举值?

Patricia Arquette
发布: 2025-01-21 21:28:10
原创
592 人浏览过

How Can I Get an Enum Value from its Description Attribute?

根据描述属性获取枚举值

前面我们介绍过一个扩展方法,用于获取枚举关联的Description属性。现在,让我们探索一个补充函数,允许我们根据其描述获取枚举。

为此,我们引入以下扩展方法:

public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach (var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("未找到。", nameof(description));
        // 或返回 default(T);
    }
}
登录后复制

使用方法:

此方法可以按如下方式调用:

var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");
登录后复制

通过提供“大熊猫”描述,扩展方法将检索相应的大熊猫枚举值。

以上是如何从其描述属性中获取枚举值?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板