c# - 为属性分配随机枚举值

标签 c# enums

您好,我正在努力完成一项任务。我需要为一个属性分配一个随机的 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 等)使事情复杂化,我需要随机发生器忽略 BlackWhite

最佳答案

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

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/

相关文章:

postgresql - 是否可以创建一个具有一定间隔的枚举类型?

java - Realm 对象类 setter 中的枚举支持和自定义逻辑

c# - Razor View 中隐藏的 HiddenFor 字段中的枚举值而不是键 (Asp.Net MVC 5)

c - 为什么在文件范围内初始化枚举类型变量时出现错误?

c++ - 使用枚举编译时多态性

c# - 发现空格时 DateTime.TryParse 应该失败

c# - GroupJoin 返回序列不包含任何元素

c# - EWS Managed API 如何区分不同的约会?

c# - LiveCharts WPF 使用实时数据慢。提高 LiveCharts 实时绘图性能

c# - MVC 3 多表单模型传递给字典