C# - 在构造函数中加载方法
有人可以解释为什么执行这个方法(在构造函数中)会抛出语法错误:
public partial class Form1 : Form
{
public Form1()
{
Load += YourPreparationHandler;
}
private void YourPreparationHandler(object sender, EventArgs e)
{
button22_Click(sender, e);
}
}
名称“button22_Click”不 存在于当前上下文中
Could someone explain why executing this method (in the constructor) throws a syntax error:
public partial class Form1 : Form
{
public Form1()
{
Load += YourPreparationHandler;
}
private void YourPreparationHandler(object sender, EventArgs e)
{
button22_Click(sender, e);
}
}
The name 'button22_Click' does not
exist in the current context
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
button22_Click
是Form1
的成员吗?检查方法是否存在,错误是不言自明的。Is
button22_Click
a member ofForm1
? Check that method exists, the error is pretty self explanatory.button22_Click
是否在任何地方定义?如果不是的话那就是问题了。Is
button22_Click
defined anywhere? That would be the problem if it isn't.通常在构造函数中有这样的内容:
表单类被设置为分部类。这是因为在 Visual Studio 中,当您将组件拖放到表单上时,VS 在幕后会使用您的更新来更新设计器文件。
因此,您将拥有
Form1.cs
Form1.Designer.cs
和可能的
Form1.xx.resx (如果您已实现全球化)
如果您查看设计器文件,您将看到 Visual Studio 正在生成代码:
我敢打赌设计器文件丢失、混乱或InitializeComponent被意外删除。在任何情况下,该对象 (button_22) 都不存在或未被引用,因此您将无法在其上引发单击事件。
Usually in the constructor there is something like this:
Form classes are set up as partial classes. This is because in Visual Studio when you drag and drop components onto a form, behind the scenes VS is updateing the designer file with your updates.
So, you will have
Form1.cs
Form1.Designer.cs
and possibly
Form1.xx.resx (if you have globalization in place)
If you look at the designer file you will see something like this that Visual Studio is code generating:
I bet the designer file is missing, messed up, or InitializeComponent was removed by accident. In any case, the object (button_22) doesn't exist or is not referenced so you will not be able to raise a click event on it.