Loop through all colors?

前端 未结 3 640
甜味超标
甜味超标 2021-01-07 04:52

I\'m working on an app in C# (Windows-Phone-7), and I\'m trying to do something simple that has me stumped.

I want to cycle through each Color in Colors, and write o

相关标签:
3条回答
  • 2021-01-07 05:24

    You can use Reflection to get all of the properties within the Colors type:

    var colorProperties = Colors.GetType().GetProperties(BindingFlags.Static | BindingFlags.Public);
    var colors = colorProperties.Select(prop => (Color)prop.GetValue(null, null));
    foreach(Color myColor in colors)
    {
        // ....
    
    0 讨论(0)
  • 2021-01-07 05:32

    Well you can do so by using this code.

         List<string> colors = new List<string>();
    
        foreach (string colorName in Enum.GetNames(typeof(KnownColor)))
        {
            //cast the colorName into a KnownColor
            KnownColor knownColor = (KnownColor)Enum.Parse(typeof(KnownColor), colorName);
            //check if the knownColor variable is a System color
            if (knownColor > KnownColor.Transparent)
            {
                //add it to our list
                colors.Add(colorName);
            }
        }
    
    0 讨论(0)
  • 2021-01-07 05:35

    You can use this helper method to get a Dictionary of each Color's name/value pair.

    public static Dictionary<string,object> GetStaticPropertyBag(Type t)
        {
            const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
    
            var map = new Dictionary<string, object>();
            foreach (var prop in t.GetProperties(flags))
            {
                map[prop.Name] = prop.GetValue(null, null);
            }
            return map;
        }
    

    Use is with:

    var colors = GetStaticPropertyBag(typeof(Colors));
    
    foreach(KeyValuePair<string, object> colorPair in colors)
    {
         Console.WriteLine(colorPair.Key);
         Color color = (Color) colorPair.Value;
    }
    

    Credit for the helper method goes to How can I get the name of a C# static class property using reflection?

    0 讨论(0)
提交回复
热议问题