随机播种问题和可能的构造函数问题

random seeding issue and probably constructor issue

我想生成一个从 1000 开始的用户 ID,每个用户递增 1(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);
    }
}

I want to generate a userID starting with 1000, incrementing by one for each user (1000, 1001, 1002, etc.).

那么你不应该尝试使用随机生成器来做到这一点,因为它会 return 随机 而不是序列号。

鉴于您的示例代码,您 (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();
    }
}