在我的主要形式中,我有一个计时器,它每隔几秒更新一次文本框中的值,代码如下:
public partial class Form1 : Form
{
static int column = 2;
static int row = 100;
System.Windows.Forms.TextBox[,] textbox = new System.Windows.Forms.TextBox[column, row];
delegate void StringParameterDelegate(int j, string value);
DisplayTimer displayTimer = new DisplayTimer();
System.Threading.TimerCallback displayCallback;
System.Threading.Timer displayTimerThread;
public Form1()
{
InitializeComponent();
//set the array for name and update time
for (int k = 0; k < column; k++)
{
for (int j = 0; j < row; j++)
{
textbox[k, j] = new System.Windows.Forms.TextBox();
textbox[k, j].Size = new Size(160, 18);
textbox[k, j].Name = "textbox_" + k + "_" + j;
if (j >= 100)
{
textbox[k, j].Location = new System.Drawing.Point((k * 160) + 20, (j * 18) + 30);
}
textbox[k, j].Visible = true;
Controls.Add(textbox[k, j]);
}
}
displayCallback = new System.Threading.TimerCallback(timeDisplay);
displayTimerThread = new System.Threading.Timer(displayCallback, displayTimer, 3000, 3000);
// more code
}
public void timeDisplay(object timerObject)
{
DisplayTimer t = (DisplayTimer)timerObject;
for (int j = 0; j < t.row; j++)
{
string value = t.outputTime[j].ToString("yyyy/MM/dd HH:mm:ss.fff");
writeToTextBox(j, value);
}
}
public void writeToTextBox(int j, string value)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(writeToTextBox), new object[] { j, value });
return;
}
// Must be on the UI thread if we've got this far
textbox[1, j].Text = value;
}
现在上面的代码运行良好,没有发生错误。但是我的程序中有 3 个表单使用相同的方法 timeDisplay 和 writeToTextBox,我必须在表单中复制代码 3 次。我试图重构这两种方法并将其放入一个新类中。我的 writeToTextBox 方法出现以下错误。
错误 1 当前上下文中不存在名称“InvokeRequired”
错误 2 当前上下文中不存在名称“BeginInvoke”
错误 3 当前上下文中不存在名称“文本框”
我如何有效地重构它?一些工作代码片段将非常有帮助,在此先感谢
编辑:下面是问题的正确代码:它运行良好,没有任何错误。谢谢都铎王朝
class DisplayTimer
{
public int numberOfRow = 0;
public int column = 0;
public DateTime[] outputTime;
public System.Windows.Forms.TextBox[,] textbox;
delegate void StringParameterDelegate(TextBox textbox, string value);
public void timeDisplay(object timerObject)
{
DisplayTimer t = (DisplayTimer)timerObject;
for (int j = 0; j < t.numberOfRow; j++)
{
string value = t.outputTime[j].ToString("yyyy/MM/dd HH:mm:ss.fff");
if (value != "0001/01/01 00:00:00.000")
{
writeToTextBox(textbox[column, j], value);
}
}
}
public void writeToTextBox(TextBox textbox, string value)
{
if (textbox.InvokeRequired)
{
textbox.BeginInvoke(new StringParameterDelegate(writeToTextBox), new object[] { textbox, value });
return;
}
// Must be on the UI thread if we've got this far
textbox.Text = value;
}
}