我是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;
}
}
}
试试看:
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);
对不起,我的语言能力,但是ThrowAmount是玩家掷骰子的次数,我认为您认为这是骰子的数量。首先赢得三场胜利的是这场比赛的赢家。我做了一个构造函数来重置抛出的数量。这就是为什么有0。那个数量是骰子的数量。
@masteroscar则不需要将其作为参数传递给构造函数,实例化时它将具有默认值0。