[英]Eliminating Random Duplicates?
我有3個子類“ Staff,Faculty,Student”,每個類都是從父類人員那里獲得用戶的第一個初始姓氏,此ID就像在運行控制台應用程序時添加4個隨機數。 我遇到的問題是所有類都獲得相同的4位數字,我該如何解決這個問題,是的,必須使用隨機數完成,我不能使用靜態計數器。
Person.cs“父類”
public class Person
{
static string title;
protected string firstName;
protected string lastName;
protected string address;
protected string gender;
protected string dateOfBirth;
protected string userID;
protected Random rnd = new Random();
學院
namespace Person
{
public class Faculty : Person
{
public Faculty(string aTitle, string aFirstName, string aLastName, string aAddress,
string aGender, string aDateOfBirth)
: base(aTitle, aFirstName, aLastName, aAddress,
aGender, aDateOfBirth)
{
this.userID = firstName.Substring(0, 1) + lastName.Substring(0, 5);
this.userID = this.userID + rnd.Next(1000, 9999);
Console.WriteLine(this.userID);
}
}
}
Staff.cs
namespace Person
{
public class Staff : Person
{
public Staff(string aTitle, string aFirstName, string aLastName, string aAddress,
string aGender, string aDateOfBirth)
: base(aTitle, aFirstName, aLastName, aAddress,
aGender, aDateOfBirth)
{
this.userID = firstName.Substring(0, 1) + lastName.Substring(0, 5);
this.userID = this.userID + rnd.Next(1000, 9999);
Console.WriteLine(userID);
}
}
}
測試班
public class PersonTest
{
static void Main(string[] args)
{
Person testPerson = new Faculty(" Mr.", "Merry ", "Lanes", " 493 Bluebane RD", "Male", " 8-06-1953\n ");
Person studentPerson = new Student(" Mr.", "Jerry ", "Panes", " 456 Greenbane RD", "Male", " 8-10-1945\n");
Person staffPerson = new Staff(" Mr.", "Joe ", "Gaines", " 495 Redbane RD", "Male", " 8-21-1989\n ");
Console.ReadLine();
}//end main
我看不到您在哪里聲明和初始化rnd
。 我會猜測它是在Person中聲明為實例成員,並在Person的構造函數中初始化的-始終默認初始化,這意味着它將時間用作種子,這意味着所有以毫秒為單位的調用都將獲得相同的種子。
將rnd
設為靜態成員,然后在靜態ctonstructor中對其進行一次初始化。
更新:這應該是所有需要的:
static readonly protected Random rnd = new Random();
(這也會更快,因為您只創建一次新的Random對象,而不是為每個對象創建一次。從時鍾創建種子非常慢。)
如果可以,建議重新考慮此設計
但是,正如您在帖子中所建議的那樣,恕我直言,一種理想的方法是使用單例或存儲(例如SQL身份)來跟蹤最后發布的UserId。
將rnd
設為靜態並立即初始化,這應該是有史以來最快的解決方案。
據我了解,rnd在您的基類中是受保護的/公共領域/財產,因此將其設為靜態將在首次訪問您的Person類型時創建隨機生成器。
public class Person
{
protected static Random rnd = new Random();
}
public class PersonImpl : Person
{
public void DoSomething()
{
int a = rnd.Next(100, 9999);
}
}
隨機數需要一個種子才能開始-它只是一天結束時的一個公式。 如果他們從同一地點開始,他們將到達同一地點。
這是一個教程:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5663283.html
我認為問題是,您要連續地初始化Random對象,並且由於系統時鍾具有有限的分辨率,因此這些對象獲得相同的種子。 解決方案是對所有三個類使用相同的Random對象。
更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.