才学习C#一周左右,在看 C#入门经典 这门书 ,看到对象这一章一个程序中的一句话不能理解,请大家指导,谢谢newButton.Click += new EventHandler(newButton_Click);
才学习,希望大家不要笑话原程序是这样的:namespace Windows_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
((Button)sender).Text = "clicked!";
Button newButton = new Button();
newButton.Text = "New Button!";
newButton.Click += new EventHandler(newButton_Click);
Controls.Add(newButton);
} private void newButton_Click(object sender, EventArgs e)
{
((Button)sender).Text = "clicked!";
}
}
}
才学习,希望大家不要笑话原程序是这样的:namespace Windows_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
((Button)sender).Text = "clicked!";
Button newButton = new Button();
newButton.Text = "New Button!";
newButton.Click += new EventHandler(newButton_Click);
Controls.Add(newButton);
} private void newButton_Click(object sender, EventArgs e)
{
((Button)sender).Text = "clicked!";
}
}
}
这是手动定义事件 如果你定义了一个控件的事件 在程序隐藏代码中可以看到和这个一样的
用重载的方法吧这个事件注册到click的监听程序中,并使用一个非默认的构造函数创建一个EventHandler对象这话没明白,可能我的理解能力不强,希望楼上的朋友耐心讲解,谢谢
“用重载的方法吧这个事件注册到click的监听程序中,并使用一个非默认的构造函数创建一个EventHandler对象 ”newButton.Click+是事件监听,看看你点没点鼠标;
事件不管字符串还是时间,最终都是0101
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
((Button)sender).Text = "clicked!"; //button1按下时,button1的text为“licked”;
Button newButton = new Button(); //新建按纽
newButton.Text = "New Button!"; //新按纽的text
newButton.Click += new EventHandler(newButton_Click); //添加新按纽的单击事件
Controls.Add(newButton); //是谁拥有了newbutton(很重要)没有这个,界面上不显示
} private void newButton_Click(object sender, EventArgs e) //新按纽的单击事件处理。
{
((Button)sender).Text = "clicked!";
}
}
}
着段话的意思是你按下了button1的时候,他的内容变为“clicked”同时动态新件一个按钮,并添加它的单击事件。如果按下他的话,他的内容也边为了“clicked”。
你也可以不用委托实现
他就是实现在界面上新建个按钮并为按钮更改名字的功能而已
你先把委托的定义以及事件这些知识看一下
不懂得的方法查下MSDN就知道了
1. 委托
a) 委托是将名称与方法的定义连接起来,类似于一个指向方法的指针,在不同的情况下可以将其指向不同的方法,但方法和委托必须具有相同的数量和类型的参数。
b) 定义委托:
[访问修饰符] delegate 返回类型 委托名([参数列表]);
例:public delegate int Call(int num1,int num2);
c) 实例化委托:
使用new关键字实例化委托
例:Call objCall = new Call(方法名);
d) 调用委托:
调用委托与调用方法类似:objCall(num1,num2);
2. 事件
a) 定义事件
[访问修饰符] event 委托名 事件名;
事件的定义需要首先定义委托,然后根据该委托定义事件。
例:
public delegate void delegateMe();
private event delegateMe eventMe;
b) 订阅事件
即添加一个委托,事件发生时该委托将调用一个方法。
例:
eventMe += new delegateMe(方法名);
c) 引发事件
if(条件)
{
事件名();
}
当满足条件时,引发该事件,此时将调用订阅此事件的对象的所有委托。
例:
if(eventMe != null)
{
eventMe();
}