您设法意识到,您需要以某种方式将第二个参数设置为Next
方法变量.太棒了!让我们开始吧:
static int RullaTärning(Random slumpObjekt)
{
int sides = 6;
int nr = slumpObjekt.Next(1, sides +1);
return nr;
}
现在,您需要做的就是从用户那里获取值,而不是硬编码:
static int RullaTärning(Random slumpObjekt, int sides)
{
int nr = slumpObjekt.Next(1, sides+1);
return nr;
}
如果您不想强制用户 Select 边数(大多数骰子将是6面),您可以使用默认设置:
static int RullaTärning(Random slumpObjekt, int sides = 6)
{
int nr = slumpObjekt.Next(1, sides+1);
return nr;
}
// Can be used as
int roll = RullaTärning(rnd); // no second param => 6 will be used
// or
int damage = RullaTärning(rnd, 16);
我总是鼓励您判断您的输入:
static int RullaTärning(Random slumpObjekt, int sides = 6)
{
// Assuming we had a requirement to allow no less than 6 sides.
if( sides < 6 ) throw new ArgumentException("Dice need at least 6 sides.", nameof(sides));
// Mind that I did not check `slumpObjekt` for null,
// because a NullReferenceException will be thrown anyway
// on the attempt to call `Next` on `null`.
int nr = slumpObjekt.Next(1, sides+1);
return nr;
}
// because there is always "that guy" who will try
int nonsense = RullaTärning(rnd, -5);
...一个非常迂腐的家伙刚刚让我提到了干净的代码和"没有魔术数字"……
const int MINIMAL_ALLOWED_SIDES = 6; // Now we know why "6" and
// we only need to change 1 place in code
// if requirement of minimal allowed sides
// changes
static int RullaTärning(Random slumpObjekt, int sides = MINIMAL_ALLOWED_SIDES)
{
if( sides < MINIMAL_ALLOWED_SIDES) throw new ArgumentException($"Dice need at least {MINIMAL_ALLOWED_SIDES} sides.", nameof(sides));
int nr = slumpObjekt.Next(1, sides+1);
return nr;
}