因此,我编写了一个快速示例来说明我在评论中暗示的内容。我使用了一个 Windows 窗体应用程序作为我的示例运行时。当表单加载时,它会从单个文件中读取名称部分,然后获取随机值以形成名称。
名称部分将存储在纯文本文件中,每行一个部分,如下所示:
前缀.txt
far
bar
dun
brat
您将对每个文件使用相同的格式(每行一个字)。
现在,有趣的部分:
public partial class Form1 : Form
{
private readonly Random _random = new Random();
private string[] _prefixParts;
private string[] _middleParts;
private string[] _suffixParts;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Only read the data from each file once as this could be expensive
_prefixParts = PopulateFromFile("prefix.txt"); // alter your path as necessary
_middleParts = PopulateFromFile("middle.txt");
_suffixParts = PopulateFromFile("suffix.txt");
}
private void button1_Click(object sender, EventArgs e)
{
// Generate a random name
randomNameLabel.Text = GetRandomName();
}
private string[] PopulateFromFile(string path)
{
return File.ReadAllLines(path);
}
private string GetRandomName()
{
// this will get a random name part from each of the arrays, concatenate and return the complete name
return GetRandomNamePart(_prefixParts) + GetRandomNamePart(_middleParts) + GetRandomNamePart(_suffixParts);
}
private string GetRandomNamePart(string[] array)
{
// this will return a random value from the array
return array[_random.Next(array.Length)];
}
}