为属性分配随机枚举值

Ros*_*oss 3 c# enums

嗨,我被赋予了一项我正在努力的任务.我需要为enum一个属性分配一个随机数.我的代码就是这个.

public enum PegColour
{
    Red, Green, Blue, Yellow, Black, White
}
Run Code Online (Sandbox Code Playgroud)

和其他看起来像这样的课程

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()
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我的GeneratePegs()方法应该,每次随机调用时指定的一个enum颜色的属性之一(Colour1,Colour2等)事项,我需要随机数发生器忽略复杂BlackWhite.

Ice*_*ind 5

枚举只是整数,因此整数可以转换为枚举.我会这样做:

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;
}
Run Code Online (Sandbox Code Playgroud)

黑色和白色永远不会被选中,因为它只从前4种颜色中随机挑选.只要你在黑白钉之前添加钉子,这个代码应该每次都有效,即使你在枚举中添加或删除钉子也是如此.因此,如果您想添加新颜色,您只需更改PegColour为以下内容:

public enum PegColour
{
    Red, Green, Blue, Yellow, Purple, Orange, Pink, Black, White
}
Run Code Online (Sandbox Code Playgroud)

你不需要改变任何其他东西!

所以你的GeneratePegs()方法应该是这样的:

public void GeneratePegs()
{
    Colour1 = GetRandomColoredPeg();
    Colour2 = GetRandomColoredPeg();
    Colour3 = GetRandomColoredPeg();
    Colour4 = GetRandomColoredPeg();
}
Run Code Online (Sandbox Code Playgroud)