您好,我正在努力完成一项任务。我需要为一个属性分配一个随机的 enum
。我的代码是这样的。
public enum PegColour
{
Red, Green, Blue, Yellow, Black, White
}
和其他看起来像这样的类
public class PegContainer
{
/// <summary>
/// Dfines the colour of the first peg
/// </summary>
public Peg Colour1 { get; set; }
/// <summary>
/// Dfines the colour of the secod peg
/// </summary>
public Peg Colour2 { get; set; }
/// <summary>
/// Dfines the colour of the third peg
/// </summary>
public Peg Colour3 { get; set; }
/// <summary>
/// Dfines the colour of the forth peg
/// </summary>
public Peg Colour4 { get; set; }
public void GeneratePegs()
{
}
}
我的 GeneratePegs()
方法应该在每次调用时随机分配一种 enum
颜色给其中一个属性 (Colour1
, Colour2
等)使事情复杂化,我需要随机发生器忽略 Black
和 White
。
最佳答案
枚举只是整数,因此整数可以转换为枚举。我会这样做:
Random rnd = new Random();
public enum PegColour
{
Red, Green, Blue, Yellow, Black, White
}
private PegColour GetRandomColoredPeg()
{
PegColour color = (PegColour)rnd.Next(0, Enum.GetNames(typeof(PegColour)).Length - 2);
return color;
}
黑色和白色永远不会被选中,因为它只会从前 4 种颜色中随机选择。只要您在黑色和白色钉子之前添加钉子,此代码应该每次都有效,即使您从枚举中添加或删除钉子也是如此。因此,如果您想添加新颜色,只需将 PegColour
更改为如下所示:
public enum PegColour
{
Red, Green, Blue, Yellow, Purple, Orange, Pink, Black, White
}
您不需要更改任何其他内容!
因此您的 GeneratePegs()
方法应该如下所示:
public void GeneratePegs()
{
Colour1 = GetRandomColoredPeg();
Colour2 = GetRandomColoredPeg();
Colour3 = GetRandomColoredPeg();
Colour4 = GetRandomColoredPeg();
}
关于c# - 为属性分配随机枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30737821/