我有一个枚举
private enum EventColors
{
Aquamarine,
Azure,
BurlyWood,
CadetBlue,
Gainsboro,
Gold,
Gray,
Khaki,
LawnGreen,
LightGreen,
LightSkyBlue,
Linen,
MediumOrchid,
MediumPurple,
MistyRose,
Olive,
OliveDrab,
Orange,
OrangeRed,
Orchid,
PaleTurquoise,
Peru,
Pink,
Plum,
RoyalBlue,
SandyBrown,
SeaGreen,
SteelBlue,
};
我从System.Drawing.Color中选择了最好的,我想随机选择一个:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
如何将随机选择的颜色从我的枚举转换为System.Drawing.Color。 ?这可能不使用开关吗?
答案 0 :(得分:1)
您可以创建Dictionary<EventColors, System.Drawing.Color>
,以这种方式填写:
Dictionary<EventColors, System.Drawing.Color> colors = new Dictionary<EventColors, System.Drawing.Color>();
colors.Add(EventColors.Aquamarine, System.Drawing.Color.Aquamarine);
colors.Add(EventColors.Azure, System.Drawing.Color.Azure);
//... other colors
然后:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
System.Drawing.Color someColor = colors[randomBar];
或强>
您可以使用反射:
Array values = Enum.GetValues(typeof(EventColors));
Random rnd = new Random();
EventColors randomBar = (EventColors)values.GetValue(rnd.Next(values.Length));
string name = Enum.GetName(typeof(EventColors), randomBar);
var type = typeof(System.Drawing.Color);
System.Drawing.Color systemDrawingColor = (System.Drawing.Color)type.GetProperty(name).GetValue(null);