温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Random number place to property
c# properties

c# - 属性的随机数位

发布于 2020-04-03 23:59:15

我是C#的新手,并且做骰子游戏。我在将随机整数值放置到属性时遇到问题。尝试了不同的变体,但没有一个起作用,只是在文本下出现了或多或少的红色波浪线。

如何将该随机运算的结果放入属性Amount?在找到1.5小时后,Google并没有帮助我。问题出在哪里?

using System;
using System.Collections.Generic;
using System.Text;
using static System.Random;

namespace DiceRollGame
{
    class Dice
    {
        private static Random randomnumber = new Random();

        public int Amount
        {
            get
            {
                return Amount;
            }

            set
            {
                Amount = value;
            }
        }
        public int ThrowAmount { get; set; }

        public Dice(int throwamount)
        {
            ThrowAmount = 0;
        }

        public static void Throw()
        {

            int numbervalue = randomnumber.Next(1, 6);

            Amount = int numbervalue;

        }

    }
}

查看更多

提问者
masteroscar
被浏览
68
Innat3 2020-01-31 20:45

试试看:

class Dice
{
    private readonly Random rnd;
    public int Amount { get; set; }
    public int ThrowAmount { get; set; }
    public Dice() => rnd = new Random();
    public void Throw() => Amount = rnd.Next(1, 7); //Random() max value is exclusive
}

用法:

Dice d = new Dice();
d.Throw();
Console.WriteLine(d.Amount);