user2799180
user2799180

Reputation: 749

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

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.

Upvotes: 6

Views: 1593

Answers (2)

AirL
AirL

Reputation: 1917

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)

Upvotes: 1

Tim S.
Tim S.

Reputation: 56556

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.

Upvotes: 7

Related Questions