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.
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 Pen
s 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
.
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 Color
s instances not metadata, you can do that with the following piece of code :
(Color)field.GetValue(null)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With