2013-04-21 58 views
4

我想用system.drwaing.color项填充我的列表以选择随机颜色并将其设置为backColor。C# - 如何添加列表中的所有system.drwaing.color项目?

这里是我的代码:

List<Color> myList = new List<Color>(); 
    //rc.Add(Color.Chartreuse); 
    //rc.Add(Color.DeepSkyBlue); 
    //rc.Add(Color.MediumPurple); 
    foreach (Color clr in System.Drawing.Color) 
    { 
     //error 
    } 
    Random random = new Random(); 
    Color color = myList[random.Next(myList.Count - 1)]; 
    this.BackColor = color; 

错误: “的System.Drawing.Color”是“型”,这是不是在给定的情况下有效

谁能给我一个手?

回答

7
public static List<Color> ColorStructToList() 
{ 
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) 
         .Select(c => (Color)c.GetValue(null, null)) 
         .ToList(); 
} 

List<Color> colorList = ColorStructToList();


private void randomBackgroundColorButton_Click(object sender, EventArgs e) 
{ 
    List<Color> myList = ColorStructToList(); 
    Random random = new Random(); 
    Color color = myList[random.Next(myList.Count - 1)]; 
    this.BackColor = color; 
} 

public static List<Color> ColorStructToList() 
{ 
    return typeof(Color).GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public) 
         .Select(c => (Color)c.GetValue(null, null)) 
         .ToList(); 
} 
+0

谢谢,但错误存在,但请给我完整的代码:( – reza 2013-04-21 12:31:17

2

this question

string[] colors = Enum.GetNames(typeof(System.Drawing.KnownColor)); 
+0

看看他的代码示例的上下文。他想用'Drawing.Color'而不是'System.String'填充数组。 – 2013-04-21 12:16:57

+0

对,理解。现在学习你的代码... – 2013-04-21 15:28:38

0

这里是你的代码:

private List<Color> GetAllColors() 
{ 
    List<Color> allColors = new List<Color>(); 

    foreach (PropertyInfo property in typeof(Color).GetProperties()) 
    { 
     if (property.PropertyType == typeof(Color)) 
     { 
      allColors.Add((Color)property.GetValue(null)); 
     } 
    } 

    return allColors; 
} 
0

根据Artxzta的回答,在VB.net中:

Imports System.Reflection 

Dim allColors As New List(Of String) 

For Each [property] As PropertyInfo In GetType(Colors).GetProperties() 
     allColors.Add([property].Name) 
Next 
相关问题