How to generate random color names in C#

后端 未结 15 1794
清酒与你
清酒与你 2020-11-29 21:57

I need to generate random color names e.g. \"Red\", \"White\" etc. How can I do it? I am able to generate random color like this:

Random randonGen = new Ran         


        
15条回答
  •  北海茫月
    2020-11-29 23:01

    I would have commented on Pih's answer; however, not enough karma. Anywho, I tried implementing this and ran into the issue of the same color being generated from multiple calls as the code was called repeatedly in quick succession (i.e. the randomGen was the same and since it is based on the clock = same results ensued).

    Try this instead:

    public class cExample
    {
        ...
        Random randomGen = new Random();
        KnownColor[] names = (KnownColor[]) Enum.GetValues(typeof(KnownColor));
        ...
        private Color get_random_color()
        {
             KnownColor randomColorName = names[randomGen.Next(names.Length)];
             return Color.FromKnownColor(randomColorName);
        }
        ...
    }
    

提交回复
热议问题