Kit.Core/LibCommon/Kit.Core.Helpers/DictionaryCollector.cs

42 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.ComponentModel;
using System.Reflection;
namespace Kit.Helpers
{
// Класс для сбора словаря
public static class DictionaryCollector
{
public static IDictionary<string, string> GetConstantsWithDescriptions<T>()
{
return GetConstantsWithDescriptions(typeof(T));
}
public static IDictionary<string, string> GetConstantsWithDescriptions(Type type)
{
var result = new Dictionary<string, string>();
// Получаем все поля в переданном статическом классе
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in fields)
{
// Проверяем, является ли поле константой
if (field.IsLiteral && !field.IsInitOnly)
{
// Получаем значение константы
var value = field.GetValue(null)?.ToString();
// Получаем атрибут Description
var attribute = field.GetCustomAttribute<DescriptionAttribute>();
if (attribute != null)
{
// Добавляем пару "значение константы" - "описание" в словарь
result[value] = attribute.Description;
}
}
}
return result;
}
}
}