C# 枚举的一些工具方法

1.获取枚举的描述字典

        public static Dictionary<string, string> GetEnumDescriptionDict(Type t)
        {
            Dictionary<string, string> enumDescDict = new ();
            if (!t.IsEnum)
            {
                return enumDescDict;
            }
            
            FieldInfo[] fields = t.GetFields();

            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    string description = field.GetXmlDocsSummary();
                    if (string.IsNullOrEmpty(description))
                    {
                        var attrDesc = field.GetCustomAttribute<DescriptionAttribute>();
                        if (attrDesc != null)
                            description = attrDesc.Description;
                    }
                    enumDescDict.Add(field.Name, description);
                }
            }
            return enumDescDict;
        }
posted @ 2023-05-19 10:50  SpringCore  阅读(96)  评论(0编辑  收藏  举报