Статический класс к словаря <строка, строка> в c#
-
26-10-2019 - |
Вопрос
У меня есть статический класс, который содержит только свойства строк. Я хочу преобразовать этот класс в словарь парных значений с key=PropName
, value=PropValue
.
Ниже приведен код, который я написал:
void Main()
{
Dictionary<string, string> items = new Dictionary<string, string>();
var type = typeof(Colors);
var properties = type.GetProperties(BindingFlags.Static);
/*Log properties found*/
/*Iam getting zero*/
Console.WriteLine("properties found: " +properties.Count());
foreach (var item in properties)
{
string name = item.Name;
string colorCode = item.GetValue(null, null).ToString();
items.Add(name, colorCode);
}
/*Log items created*/
Console.WriteLine("Items in dictionary: "+items.Count());
}
public static class Colors
{
public static string Gray1 = "#eeeeee";
public static string Blue = "#0000ff";
}
Выход
properties found: 0
Items in dictionary: 0
Это не чтение каких -либо свойств - может ли кто -нибудь сказать мне, что не так с моим кодом?
Решение
Участники в вашем Colors
класс нет характеристики но поля.
Использовать GetFields
В месте метода GetProperties.
Вы можете получить что -то вроде (также не изменение призыв GetValue
):
var properties = type.GetFields(BindingFlags.Static);
/*Log properties found*/
/*Iam getting zero*/
Console.WriteLine("properties found: " +properties.Count());
foreach (var item in properties)
{
string name = item.Name;
string colorCode = item.GetValue(null).ToString();
items.Add(name, colorCode);
}
Другие советы
Вы можете использовать LINQ для конденсации преобразования в пару строк:
var type = typeof(Colors);
var fields = type.GetFields().ToDictionary(f => f.Name, f => f.GetValue(f).ToString());
Использовать это:
var properties = type.GetFields(BindingFlags.Static|BindingFlags.Public);
Не связан с StackOverflow