更新时间:2023-02-06 08:54:48
首先:调用非虚拟构造函数中的方法。你在哪里读到那里? (注意:调用 方法可能是一个问题;它不是一个自动的no-no,但你需要非常仔细地观察你在做什么。)
First off: there is nothing wrong with calling non-virtual methods in the constructor. Where did you read that there was? (Note: calling virtual methods can be a problem; it is not an automatic no-no, but you need to watch what you are doing very carefully).
另外,每次 GenerateRandomNumber $时生成一个新的
随机
c $ c>被调用。您可以将 Random
实例提取到字段以修复:
As an aside, it seems wasteful to generate a new Random
instance every time GenerateRandomNumber
is called. You can extract the Random
instance to a field to fix that:
class RandomNumberHandler
{
private readonly Random random = new Random();
private int randomNumber;
public RandomNumberHandler()
{
this.randomNumber = GenerateRandomNumber();
}
private int GenerateRandomNumber()
{
return this.random.Next(3000) + 1000;
}
}
但这又引出了另一个问题:if GenerateRandomNumber
在每个实例的生命周期(在构造函数中)只调用一次,那么创建一个新的 Random
每个对象。因此,下一个逻辑步骤是使 random
为 static
。这意味着 GenerateRandomNumber
也可以变成 static
(确实,它必须):
But this raises another question: if GenerateRandomNumber
is only called once in each instance's lifetime (in the constructor), then it doesn't make sense to create a new Random
for each object. So the next logical step is to make random
be static
. This means that GenerateRandomNumber
can also become static
(and indeed, it has to):
class RandomNumberHandler
{
private static readonly Random Random = new Random();
private int randomNumber;
public RandomNumberHandler()
{
this.randomNumber = GenerateRandomNumber();
}
private static int GenerateRandomNumber()
{
return Random.Next(3000) + 1000;
}
}