문제

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?

도움이 되었습니까?

해결책

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):

                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);
                }

다른 팁

You can use linq to condense the conversion to a couple of lines:

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

Use this:

var properties = type.GetFields(BindingFlags.Static|BindingFlags.Public);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top