了解C#中的事件和事件处理程序

本文翻译自:Understanding events and event handlers in C#

I understand the purpose of events, especially within the context of creating user interfaces. 我理解事件的目的,特别是在创建用户界面的环境中。 I think this is the prototype for creating an event: 我认为这是创建活动的原型:

public void EventName(object sender, EventArgs e);

What do event handlers do, why are they needed, and how do I to create one? 事件处理程序做了什么,为什么需要它们,以及如何创建一个?


#1楼

参考:https://stackoom.com/question/3MxW/了解C-中的事件和事件处理程序


#2楼

Just to add to the existing great answers here - building on the code in the accepted one, which uses a delegate void MyEventHandler(string foo) ... 只是为了在这里添加现有的优秀答案 - 在已接受的代码中构建代码,它使用delegate void MyEventHandler(string foo) ...

Because the compiler knows the delegate type of the SomethingHappened event, this: 因为编译器知道SomethingHappened事件的委托类型,所以:

myObj.SomethingHappened += HandleSomethingHappened;

Is totally equivalent to: 完全等同于:

myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);

And handlers can also be unregistered with -= like this: 处理程序也可以取消注册 -=这样:

// -= removes the handler from the event's list of "listeners":
myObj.SomethingHappened -= HandleSomethingHappened;

For completeness' sake, raising the event can be done like this, only in the class that owns the event: 为了完整起见,可以像这样完成事件,只在拥有事件的类中:

//Firing the event is done by simply providing the arguments to the event:
var handler = SomethingHappened; // thread-local copy of the event
if (handler != null) // the event is null if there are no listeners!
{
    handler("Hi there!");
}

The thread-local copy of the handler is needed to make sure the invocation is thread-safe - otherwise a thread could go and unregister the last handler for the event immediately after we checked if it was null , and we would have a "fun" NullReferenceException there. 需要处理程序的线程本地副本以确保调用是线程安全的 - 否则一个线程可以在我们检查它是否为null之后立即取消注册该事件的最后一个处理程序,并且我们将有一个“有趣”那里有NullReferenceException


C# 6 introduced a nice short hand for this pattern. C#6为这种模式引入了一个很好的简短手。 It uses the null propagation operator. 它使用空传播运算符。

SomethingHappened?.Invoke("Hi there!");

#3楼

My understanding of the events is; 我对这些事件的理解是;

Delegate: 代表:

A variable to hold reference to method / methods to be executed. 用于保存对要执行的方法/方法的引用的变量。 This makes it possible to pass around methods like a variable. 这使得传递变量等方法成为可能。

Steps for creating and calling the event: 创建和调用事件的步骤:

  1. The event is an instance of a delegate 该事件是委托的实例

  2. Since an event is an instance of a delegate, then we have to first define the delegate. 由于事件是委托的实例,因此我们必须首先定义委托。

  3. Assign the method / methods to be executed when the event is fired ( Calling the delegate ) 分配事件被触发时要执行的方法/方法( 调用委托

  4. Fire the event ( Call the delegate ) 解雇事件( 致电代表

Example: 例:

using System;

namespace test{
    class MyTestApp{
        //The Event Handler declaration
        public delegate void EventHandler();

        //The Event declaration
        public event EventHandler MyHandler;

        //The method to call
        public void Hello(){
            Console.WriteLine("Hello World of events!");
        }

        public static void Main(){
            MyTestApp TestApp = new MyTestApp();

            //Assign the method to be called when the event is fired
            TestApp.MyHandler = new EventHandler(TestApp.Hello);

            //Firing the event
            if (TestApp.MyHandler != null){
                TestApp.MyHandler();
            }
        }

    }   

}

#4楼

I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate). 我同意KE50,除了我将'event'关键字视为'ActionCollection'的别名,因为该事件包含要执行的操作集合(即委托)。

using System;

namespace test{

class MyTestApp{
    //The Event Handler declaration
    public delegate void EventAction();

    //The Event Action Collection 
    //Equivalent to 
    //  public List<EventAction> EventActions=new List<EventAction>();
    //        
    public event EventAction EventActions;

    //An Action
    public void Hello(){
        Console.WriteLine("Hello World of events!");
    }
    //Another Action
    public void Goodbye(){
        Console.WriteLine("Goodbye Cruel World of events!");
    }

    public static void Main(){
        MyTestApp TestApp = new MyTestApp();

        //Add actions to the collection
        TestApp.EventActions += TestApp.Hello;
        TestApp.EventActions += TestApp.Goodbye;

        //Invoke all event actions
        if (TestApp.EventActions!= null){
            //this peculiar syntax hides the invoke 
            TestApp.EventActions();
            //using the 'ActionCollection' idea:
            // foreach(EventAction action in TestApp.EventActions)
            //     action.Invoke();
        }
    }

}   

}

#5楼

//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyDelegate(string foo);

//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyDelegate MyEvent;

//Here is some code I want to be executed
//when SomethingHappened fires.
void MyEventHandler(string foo)
{
    //Do some stuff
}

//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.MyEvent += new MyDelegate (MyEventHandler);

#6楼

publisher: where the events happen. 出版商:事件发生的地方。 Publisher should specify which delegate the class is using and generate necessary arguments, pass those arguments and itself to the delegate. Publisher应指定该类正在使用哪个委托并生成必要的参数,将这些参数及其自身传递给委托。

subscriber: where the response happen. subscriber:响应发生的地方。 Subscriber should specify methods to respond to events. 订阅者应指定响应事件的方法。 These methods should take the same type of arguments as the delegate. 这些方法应采用与委托相同类型的参数。 Subscriber then add this method to publisher's delegate. 订阅者然后将此方法添加到发布者的委托。

Therefore, when the event happen in publisher, delegate will receive some event arguments (data, etc), but publisher has no idea what will happen with all these data. 因此,当事件发生在发布者中时,委托将接收一些事件参数(数据等),但发布者不知道所有这些数据会发生什么。 Subscribers can create methods in their own class to respond to events in publisher's class, so that subscribers can respond to publisher's events. 订阅者可以在自己的类中创建方法来响应发布者类中的事件,以便订阅者可以响应发布者的事件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#,文本框输入后立即触发事件的方法有多种。其一种方法是使用TextChanged事件。当文本框的内容发生变化时,TextChanged事件会被触发。你可以在事件处理程序编写代码来响应文本框内容的变化。例如,在窗体Form1,你可以为textBox1绑定TextChanged事件,然后在事件处理程序执行你想要的操作。以下是一个示例代码: private void textBox1_TextChanged(object sender, EventArgs e) { // 在这里编写你的代码,响应文本框内容的变化 // 例如,你可以调用RefreshTextBox方法来刷新Form2的文本框内容 RefreshTextBox(textBox1.Text); } 在上述代码,当textBox1的内容发生变化时,TextChanged事件会被触发,然后调用RefreshTextBox方法来刷新Form2的文本框内容。请注意,RefreshTextBox方法需要在Form2定义,并且必须是public的,以便在Form1访问。你可以参考引用\[1\]的代码来实现RefreshTextBox方法。 另外,还有其他一些事件可以用于监听文本框输入的变化,如KeyUp、KeyPress和KeyDown事件。这些事件在不同的情况下有不同的触发时机和特点。例如,KeyUp事件会在按键释放时触发,而KeyPress事件会在按键按下时触发。你可以根据你的需求选择适合的事件来监听文本框输入的变化。你可以参考引用\[2\]和引用\[3\]的代码来了解如何使用这些事件。 总之,你可以使用TextChanged事件或其他适合的事件来实现在文本框输入后立即触发事件的功能。希望这些信息对你有帮助! #### 引用[.reference_title] - *1* *2* [文本框内容自动投影,浅谈C#事件的写法与应用](https://blog.csdn.net/ylq1045/article/details/127034812)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [C#文本框KeyPress事件触发回车事件调用相关函数。](https://blog.csdn.net/qq_35604488/article/details/107222214)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值