静态类到 Dictionary在 c# 中
我有一个仅包含字符串属性的静态类。我想将该类转换为带有 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
它没有读取任何属性 - 谁能告诉我我的代码有什么问题吗?
I have a static class which only contains string properties. I want to convert that class into a name-value pair dictionary with key=PropName
, value=PropValue
.
Below is the code I have written:
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";
}
Output
properties found: 0
Items in dictionary: 0
It's not reading any properties - can anybody tell me what's wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Colors
类中的成员不是属性 但字段。在GetProperties 方法的位置。
您最终可能会得到类似的结果(也不是对 GetValue 的调用的更改):
The members in your
Colors
class are no properties but fields.Use
GetFields
in the place of the GetProperties method.You might end up with something like (also not the change in the call to
GetValue
):您可以使用 linq 将转换压缩为几行:
You can use linq to condense the conversion to a couple of lines:
使用这个:
Use this: