简体   繁体   English

C Sharp事件处理程序

[英]C Sharp Event Handler

private void button1_Click(object sender, EventArgs e)
{
    Button source = (Button)sender;
    MessageBox.Show("The message inside the button is " + source.Text);
}

I am following a tutorial on C sharp's Event Handler , I was a Python user, 我正在学习有关C Sharp事件处理程序的教程,我是Python用户,

public static void Main()
{
    Message myMessage = new Message();
    myMessage.ShowMessage += new MessageHandler(myMessage.DisplayMessage);
}

I kind of know the basic syntax of creating new instances of a class now, but I don't get why there is a bracket for the Button in the first line.What are the differences between these two codes ? 我有点知道现在创建类的新实例的基本语法,但是我不明白为什么第一行的Button带有括号,这两个代码有什么区别?

In c# every class is inherited from object class. 在c#中,每个类都从object类继承。 as Object is a parent class it can be used to instantiate any child class. 由于Object是父类,因此可以用于实例化任何子类。 so here when we receive an object class instance we expect it to be a Button so we parse it into a Button object 所以在这里,当我们收到一个object类实例时,我们期望它是一个Button因此我们将其解析为Button对象

private void button1_Click(object sender, EventArgs e)

here sender is specified as an object type variable. 在此,将sender指定为对象类型变量。

Button source = (Button)sender;

Here that object variable sender is parsed into a Button object and save in a Button Type variable 在这里,该对象变量sender被解析为一个Button对象,并保存在Button Type变量中

Here (Button) is used to cast object sender to button type because you want the type in button. 这里(按钮)用于将对象发送方转换为按钮类型,因为您需要按钮中的类型。 and in second example as you have mentioned its creating instance of Message class. 在第二个示例中,正如您提到的,它是Message类的创建实例。

For more information go through this 欲了解更多信息,请通过此

http://msdn.microsoft.com/en-IN/library/ms173105.aspx http://msdn.microsoft.com/zh-CN/library/ms173105.aspx

Typecasting in C# C#中的类型转换

sender is an object . sender是一个object In order you get the Text property of the button, whose click handler is button1_Click , you have to cast the sender to an object of type Button , in order later get source.Text . 为了获得按钮的Text属性(其单击处理程序为button1_Click ,必须将sender转换为Button类型的对象,以便稍后获取source.Text

Actually, the sender is the control that the action is for. 实际上, sender是操作所针对的控件。 Because all the types in .NET inherit the base type System.Object , in order you get a specific property of the button, you have to cast the sender to an object of type Button . 由于.NET中的所有类型都继承了基本类型System.Object ,因此为了获得按钮的特定属性,必须将发送方强制转换为类型为Button的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM