我正在创建一个控制台应用程序来学习c#,其中我有一个买方类,其中包含生成随机名称和cpf编号的方法(类似于社会安全号码)。
在Main方法中,我使用for循环创建了10个买方类实例的买方列表。
问题是:当我运行应用程序时,会创建10个相同的实例,当我逐步调试它时,会创建10个不同的实例。
在进入下一个循环之前,如何强制应用程序完成生成名称和数字的方法?
如果需要,我可以稍后发布买家类。
谢谢!
static void Main(string[] args)
{
List<Buyer> buyers = new List<Buyer>();
for (int i = 0; i < 10; i++)
{
buyers.Add(new Buyer());
Console.WriteLine(buyers[i].name.ToString() + " " + buyers[i].cpfNumber.ToString());
}
Console.WriteLine(buyers.Count.ToString());
Console.ReadLine();
}
买方类
class Buyer
{
public string cpfNumber { get; set; }
public string name { get; set; }
public string email { get; set; }
public Buyer()
{
cpfNumber = generateCpf();
name = generateName();
}
public string generateName()
{
Random random = new Random();
string[] names = new string[]
{
"Celestine",
"Nichole",
"Patti",
"Titus",
"Betsy",
"Gabrielle",
"Alisha",
"Elena",
"Shena",
"Ruthann",
"Coletta",
"Sherlyn",
"Wei",
"Donella",
"Eleonor",
"Arden",
"Milford",
"Isaac",
"Evia",
"Shelley"
};
string[] surnames = new string[]
{
"Barnes",
"Harmon",
"Lamb",
"Nicholson",
"Andrade",
"Lara",
"Gillespie",
"Hodge",
"Reynolds",
"Camacho",
"Franco",
"Costa",
"Vasquez",
"Hayden",
"Bowen",
"Hernandez",
"Berg",
"Patterson",
"Robertson",
"Salinas"
};
name = names[random.Next(0, 19)].ToString() + " " + surnames[random.Next(0, 19)].ToString();
return name;
}
public string generateCpf()
{
#region generateCpf_variables
//array of cpf digit generated in loop
int[] cpfDigit;
//cpfDigit * weight to calculate the first verification digit
int[] firstDigitSeed;
int[] secondDigitSeed;
//first verification digit sum
int firstDigitSum = 0;
int secondDigitSum = 0;
//first verification digit
int firstDigit = 0;
int secondDigit = 0;
#endregion
//9 basic digits of cpf + verification digit
cpfDigit = new int[10];
//multiplication of cpfDigit with weight (range between 2 and 10)
firstDigitSeed = new int[8];
//multiplication of cpfDigit with weight (range between 2 and 10)
secondDigitSeed = new int[8];
Random random = new Random();
//loop to generate cpf seeds and firstDigit calculus
for (int i = 0; i < 8; i++)
{
//random cpf digit
cpfDigit[i] = random.Next(0,10);
//product of cpf digit and verification weight
firstDigitSeed[i] = cpfDigit[i] * (10 - i);
//sum of firstDigitSeeds
firstDigitSum += firstDigitSeed[i];
}
if (firstDigitSum % 11 >= 2)
{
firstDigit = 11 - (firstDigitSum % 11);
}
cpfDigit[9] = firstDigit;
for (int i = 0; i < 8; i++)
{
secondDigitSeed[i] = cpfDigit[i] * (11 - i);
secondDigitSum += secondDigitSeed[i];
}
//second verification number calculator
if (secondDigitSum % 11 >= 2)
{
secondDigit = 11 - (firstDigitSum % 11);
}
foreach (int item in cpfDigit)
{
cpfNumber += item.ToString();
}
cpfNumber += secondDigit.ToString();
return cpfNumber;
}
}