随机种子设定问题和可能的构造函数问题



我想生成一个从 1000 开始的用户 ID,为每个用户(1000、1001、1002 等)递增一个。两个位置似乎都没有播种随机语句......(在构造函数或主函数中)。为什么我的随机语句在以下代码中没有使用 1000 种子正确初始化?

public class Student
{
    public string FullName { get; set; }
    public int StudentID { get; set; }
    //constructor to initialize FullName and StudentID
    public Student(string name, int ID)
    {
        FullName = name;
        Random rnd = new Random();
        StudentID = rnd.Next(1000, 1050); // creates a number greater than 1000
        return;
    }
    public override string ToString()
    {
        return string.Format("ID: {0}n Name: {1}", StudentID, FullName);
    }
}
public class StudentTest
{
    static void Main(string[] args)
    {
        Student student1 = new Student("Amy Lee", 1000);
        Student student2 = new Student("John Williams", 1001);
        Console.WriteLine(student1);
        Console.WriteLine(student2);
        Console.WriteLine("nPress any key to exit program");
        Console.ReadKey();
    }
}

Random生成随机数,而不是顺序数。

声明一个 int 变量并为每个StudentID递增它。

public class Student
{
    public string FullName { get; set; }
    public int StudentID { get; set; }
    private static int _currentId = 1000;
    public Student(string name)
    {
        FullName = name;
        StudentID = _currentId++;
        return;
    }
    public override string ToString()
    {
        return string.Format("ID: {0}n Name: {1}", StudentID, FullName);
    }
}

我想生成一个从 1000 开始的用户 ID,每个用户递增一个(1000、1001、1002 等)。

然后,您不应该尝试使用随机生成器来执行此操作,因为它将返回随机数而不是序列号。

给定您的示例代码,其中 (1) 不使用线程,(2) 不使用数据库 (3) 并且不保存创建的Student实例,实现所需内容的最简单方法如下:

public class Student
{
    private static int _curID = 1000;
    public static int GenerateNextID()
    {
        var id = _curID;
        _curID++;
        return id;
    }
    public string FullName { get; set; }
    public int StudentID { get; private set; }
    //constructor to initialize FullName and StudentID
    public Student(string name, int ID)
    {
        FullName = name;
        StudentID = ID;
    }
    public override string ToString()
    {
        return string.Format("ID: {0}n Name: {1}", StudentID, FullName);
    }
}

并像这样使用它:

public class StudentTest
{
    static void Main(string[] args)
    {
        Student student1 = new Student("Amy Lee", Student.GenerateNextID());
        Student student2 = new Student("John Williams", Student.GenerateNextID());
        Console.WriteLine(student1);
        Console.WriteLine(student2);
        Console.WriteLine("nPress any key to exit program");
        Console.ReadKey();
    }
}

最新更新