如果条件(“file.length()< 0”)为真,我想触发BUTTON_CLICK事件。我尝试如下,但我收到错误,因为“WindowsFormsApplication1.Form1.info是一个'字段',但用作'类型'”。 你能否提供你的意见?谢谢。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int flag;
public Form1()
{
InitializeComponent();
}
FileInfo info = new FileInfo("c:\\test.txt");
if (info.Length > 0) // throws an error "invalid token if in class"
flag= 1; //throws an error "WindowsFormsApplication1.Form1.info
is a 'field' but used as a 'type' "
//similar error for flag as for info
if(flag==1) //similar error for flag as for info
{
private void button1_Click(object sender, EventArgs e)
{
//Code for Redirection to New Form
}
}
}
}
答案 0 :(得分:1)
您不能将ifhandler放在if语句中,但可以触发按钮单击。将if语句修改为。
if(flag==1)
{
button1.PerformClick();
}
此外,所有抛出错误的代码都直接在类中,它们应该在方法中。将您的代码修改为。
private void CheckFile()
{
FileInfo info = new FileInfo("c:\\test.txt");
if (info.Length > 0)
flag=1;
if(flag==1)
{
button1.PerformClick();
}
}
然后,您可以在需要的地方拨打CheckFile();
来检查文件中的数据大小是否为> 0
答案 1 :(得分:1)
您的代码无法编译。原因如下:
以下是可行的代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int flag;
FileSystemWatcher watcher = new FileSystemWatcher();
public Form1()
{
InitializeComponent();
watcher.Path = @"C:\";
watcher.Filter = "test.txt";
watcher.Changed += watcher_Changed;
watcher.EnableRaisingEvents = true;
}
private void SetFlag()
{
FileInfo info = new FileInfo("c:\\test.txt");
if (info.Length > 0)
flag= 1;
}
private void CheckFlag()
{
if(flag==1)
{
button1.PerformClick();
}
}
private void button1_Click(object sender, EventArgs e)
{
//Code for Redirection to New Form
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
SetFlag();
CheckFlag();
}
}
}
现在你可以调用方法SetFlag()
来设置标志。并使用方法CheckFlag()
来检查标志。
在此示例中,我使用FileSystemWatcher
来捕获所有文件更改,并在事件SetFlag()
的处理程序内调用CheckFlag()
和Changed
您可以使用button1.PerformClick()
button1_Click(this, EventArgs.Empty)
答案 2 :(得分:0)
<强>方法1 强>
button1.PerformClick();
<强>方法2 强>
this.button1.Click += new EventHandler(button1_Click);
答案 3 :(得分:0)
这个
if (info.Length > 0) // throws an error "invalid token if in class"
flag= 1; //throws an error "WindowsFormsApplication1.Form1.info
//is a 'field' but used as a 'type' "
和此代码
if(flag==1) //similar error for flag as for info
{
}
会抛出编译时错误,因为这是类方法的代码而不是类本身
A class is like a blueprint. It defines the data and behavior of a type。基本上,c#类只能包含方法,属性,字段,事件,委托和嵌套类。
所以你的课应该是这样的:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += button1_Click;
}
private void button1_Click(object sender, EventArgs e)
{
FileInfo info = new FileInfo("c:\\test.txt");
if (info.Length > 0)
{
//Code for Redirection to New Form
}
}
}
答案 4 :(得分:0)
你不能把if-else语句放在类中,你可以将它放入方法中。试试这个:
private void button1_Click(object sender, EventArgs e)
{
FileInfo info = new FileInfo("c:\\test.txt");
if (info.Length > 0) flag = 1;
if(flag==1)
{
//Code for Redirection to New Form
}
}