Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through System.Drawing.Color struct and use it to create System.Drawing.Pen

Tags:

c#

struct

I would like to iterate through the System.Drawing.Color struct and use it to init a pen list.

I tried it like this, but the type of field is not Fitting:

colorList = new List<System.Drawing.Pen>();

        foreach (var field in typeof(System.Drawing.Color).GetFields())
        {
            if (field.FieldType.Name == "Color" && field.Name != null)
            {
                colorList.Add(new System.Drawing.Pen(field, (float)1));
            }
        }

Please help me out.

like image 891
user2799180 Avatar asked Oct 24 '13 20:10

user2799180


2 Answers

Except for Color.Empty, they're properties, not fields:

var colorList = new List<System.Drawing.Pen>();

foreach (var prop in typeof(System.Drawing.Color).GetProperties(BindingFlags.Public | BindingFlags.Static))
{
    if (prop.PropertyType == typeof(System.Drawing.Color))
    {
        colorList.Add(new System.Drawing.Pen((System.Drawing.Color)prop.GetValue(null), 1f));
    }
}

This produces Pens with 141 colors with the version I'm running, should correspond to the list at Color Properties. It does not return Empty, though it does have Transparent. Also, I changed from (float)1 to 1f. The f tells the compiler that's a float literal, more concisely than casting 1 to float.

like image 171
Tim S. Avatar answered Sep 19 '22 23:09

Tim S.


Maybe you can try to change this in your code:

colorList.Add(new System.Drawing.Pen((Color)field.GetValue(null), (float)1));

field is just a FieldInfo instance and this is what it really is (from MSDN) :

Discovers the attributes of a field and provides access to field metadata.

But what you need is to get Colors instances not metadata, you can do that with the following piece of code :

(Color)field.GetValue(null)
like image 27
AirL Avatar answered Sep 19 '22 23:09

AirL