如何在一个类的构造函数中生成一个随机数在C# [英] How to generate a random number in the constructor of a class in C#
问题描述
我知道,在C#中的类的构造函数中调用一个方法并不是一个好习惯,但我坚持一些奇怪的东西。我的问题是,当我创建一个类的对象,我需要在我的对象中分配一个字段随机数。
I know that it is not a good practice to call a method in the constructor of a class in C# but I stuck on something strange. My problem is that when I create an object of my class I need to assign a field in my object with a random number.
例如
class RandomNumberHandler
{
private int randomNumber;
public RandomNumberHandler()
{
this.randomNumber = GenerateRandomNumber();
}
private int GenerateRandomNumber()
{
return (new Random()).Next(3000) + 1000;
}
}
在我的例子中,我需要一个四位数字。我想在类中创建的随机数,其中我创建的对象,并将其作为参数传递给构造函数,但在其他类中生成一个随机数似乎不是一个很好的主意,因为我试图实现强的内聚为我的课。我在这里做一个高质量的代码课程在我的大学,我寻找最好的方法。欢迎任何想法如何做到这一点:)
In my case I need a four digit number. I thought of generating the random number in the class where I am creating the object and passing it as a parameter to the constructor but generating a random number in the other class does not seem a very good idea either because I am trying to achieve strong cohesion for my classes. I am doing this for a "High quality code" course in my university and I am looking for the best approach. Any ideas how to do this are welcome :)
推荐答案
首先:调用非虚拟构造函数中的方法。你在哪里读到那里? (注意:调用 方法可能是一个问题;它不是一个自动的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;
}
}
这篇关于如何在一个类的构造函数中生成一个随机数在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!