我想生成一个以1000开头的用户ID,为每个用户递增一个(1000,1001,1002等)。种子随机语句的位置似乎都没有种子...(在构造函数或main中)。为什么我的随机语句没有在以下代码中正确初始化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();
}
}
答案 0 :(得分:2)
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);
}
}
答案 1 :(得分:0)
我想生成一个以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();
}
}