简体   繁体   中英

How do i create a List of all colors there are from Color?

Tried this now:

KnownColor[] colors = Enum.GetValues(typeof(KnownColor));
            foreach (KnownColor knowColor in colors)
            {
                Color color = Color.FromKnownColor(knowColor);
            }

But im getting error on Enum.GetValues(typeof(KnownColor));

Error 14 Cannot implicitly convert type 'System.Array' to 'System.Drawing.KnownColor[]'. An explicit conversion exists (are you missing a cast?)

In the end i want to have a List with all colors inside so i can use the List later with the colors. today i can make Color.Red or Color.Green... I want that i will have a List of all the colors on the Form1 and i will be able to select each time another color and it will change to the selected color.

You need to cast the array:

KnownColor[] colors = (KnownColor[])Enum.GetValues(typeof(KnownColor));

Alternatively, you can leave colors as an Array (either explicitly typed or implicitly typed) since your foreach iterator is typed as a KnownColor . This would work too:

var colors = Enum.GetValues(typeof(KnownColor));
foreach (KnownColor knowColor in colors)
{
    Color color = Color.FromKnownColor(knowColor);
}

pswg has explained what's wrong with the existing code, but I'd probably just use LINQ to do it all in one go:

var colors = Enum.GetValues(typeof(KnownColor))
                 .Cast<KnownColor>() // Or cast the array
                 .Select(Color.FromKnownColor)
                 .ToList();

That will give you a List<Color> - it's not really clear what you mean by being able to select colours...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM