public Color RetrieveRandomColorFromList(int index)
{
Color[] colors = new Color[] { Color.Black, Color.Red, Color.Blue,
Color.DarkOrange, Color.DarkRed, Color.DarkGreen, Color.DarkViolet};
//Color[] colors = RetrieveKnownColorList();
int count = colors.Length;
int[] array = new int[count];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
Permute<int>(array);
return colors[array[index]];
}
static void Permute<T>(T[] array)
{
Random random = new Random();
for (int i = 1; i < array.Length; i++)
{
Swap<T>(array, i, random.Next(0, i));
}
}
static void Swap<T>(T[] array, int indexA, int indexB)
{
T temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
}
private Color[] RetrieveKnownColorList()
{
string[] colorArray = Enum.GetNames(typeof(System.Drawing.KnownColor));
Color[] knownColorArray = new Color[colorArray.Length];
int i=0;
foreach (string colorName in colorArray)
{
knownColorArray[i] = Color.FromName(colorName);
i++;
}
return knownColorArray;
}
使用时,直接 RetrieveRandomColorFromList(索引号) 即可。