加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:46:13 所属栏目:百科 来源:网络整理
导读:嗨,我被赋予了一项我正在努力的任务.我需要为属性分配一个随机枚举.我的代码就是这个. public enum PegColour{ Red,Green,Blue,Yellow,Black,White} 和其他看起来像这样的课程 public class PegContainer{ /// summary /// Dfines the colour of the first p
嗨,我被赋予了一项我正在努力的任务.我需要为属性分配一个随机枚举.我的代码就是这个.

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()方法应该,每次调用它时,将其中一个枚举颜色随机分配给其中一个属性(Colour1,Colour2等),以使问题变得复杂,我需要随机函数忽略黑白.

解决方法

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

Random rnd = new Random();

public enum PegColour
{
    Red,White
}

private PegColour GetRandomColoredPeg()
{
    PegColour color = (PegColour)rnd.Next(0,Enum.GetNames(typeof(PegColour)).Length - 2);
    return color;
}

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

public enum PegColour
{
    Red,Purple,Orange,Pink,White
}

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

所以你的GeneratePegs()方法应该如下所示:

public void GeneratePegs()
{
    Colour1 = GetRandomColoredPeg();
    Colour2 = GetRandomColoredPeg();
    Colour3 = GetRandomColoredPeg();
    Colour4 = GetRandomColoredPeg();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读