Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 静态类到字典<;字符串,字符串>;在c中#_C#_Static_Static Classes - Fatal编程技术网

C# 静态类到字典<;字符串,字符串>;在c中#

C# 静态类到字典<;字符串,字符串>;在c中#,c#,static,static-classes,C#,Static,Static Classes,我有一个只包含字符串属性的静态类。我想将该类转换为一个名值对字典,其中包含key=PropName,value=PropValue 以下是我编写的代码: void Main() { Dictionary<string, string> items = new Dictionary<string, string>(); var type = typeof(Colors); var pro

我有一个只包含字符串属性的静态类。我想将该类转换为一个名值对字典,其中包含
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";
    }

它没有读取任何属性-有人能告诉我我的代码有什么问题吗?

您的
Colors
类中的成员不是但是

用于代替GetProperties方法

您可能会得到类似的结果(也不是对
GetValue
调用的更改):

使用以下命令:

var properties = type.GetFields(BindingFlags.Static|BindingFlags.Public);

可以使用linq将转换压缩为几行:

var type = typeof(Colors);
var fields = type.GetFields().ToDictionary(f => f.Name, f => f.GetValue(f).ToString());

那么有没有办法编一本字典!!将对
GetProperties
的调用替换为
GetFields
,对
GetValue
的调用应该只有一个参数(null,因为它们是静态字段)。您是否也使用了
BindingFlags.Public
?您应该将字段设置为只读,以获取帮助。你的答案被高估了,我不能接受,因为GvS在你回答之前就回答了,而我只能接受一个答案。@Rusi-GvS实际上回答了这个问题,所以完全应该得到被接受的答案。
var properties = type.GetFields(BindingFlags.Static|BindingFlags.Public);
var type = typeof(Colors);
var fields = type.GetFields().ToDictionary(f => f.Name, f => f.GetValue(f).ToString());