如何让一个方法使用其他方法中的变量?
void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string fullPathname = openFileDialog.FileName;
FileInfo src = new FileInfo(fullPathname);
fileName.Text = src.Name;
source.Text = "";
TextReader reader = src.OpenText();
string line = reader.ReadLine();
int count = 0;
while (line != null)
{
line = reader.ReadLine();
count += 1;
}
string[] quest;
quest = new string[count];
int yes = 1;
TextReader second = src.OpenText();
while (yes != count)
{
quest[yes] = second.ReadLine();
yes += 1;
}
Random ran = new Random();
source.Text += quest[ran.Next(1, count)];
reader.Close();
}
void bottom1_Click(object sender, RoutedEventArgs e)
{
source.Text += quest[ran.Next(1, count)];
}
[解决办法]
将
string[] quest;
int count = 0;
Random ran = new Random();
放到方法外面
[解决办法]
string[] quest;
int count = 0;
private void ReadText()
{
string path = @"E:\1.txt";
FileInfo fileInfo = new FileInfo(path);
TextReader reader = fileInfo.OpenText();
List<string> txtList = new List<string>();
string text = reader.ReadLine();
while (!string.IsNullOrEmpty(text))
{
txtList.Add(text);
text = reader.ReadLine();
}
reader.Close();
count = txtList.Count;
quest = txtList.ToArray();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(GetRandomLine());
}
private string GetRandomLine()
{
Random ran = new Random();
return quest[ran.Next(0, count - 1)];
}
感觉这样实现会好一点