KSO-c#中 event事件的简单使用

定义

事件是一种特殊的多播委托,仅可以从声明事件的类或结构(发布服务器类)中对其进行调用。 如果其他类或结构订阅该事件,则在发布服务器类引发该事件时,将调用其事件处理程序方法。 有关详细信息和代码示例,请参阅事件和委托。

可以将事件标记为public、private、protected、internal、protected internal 或 private protected。 这些访问修饰符定义该类的用户访问该事件的方式。 有关详细信息,请参阅访问修饰符。

event

项目

event 关键字用于声明发布服务器类中的事件。

示例
下面的示例演示如何声明和引发使用 EventHandler 作为基础委托类型的事件。 要查看完整代码示例了解如何使用泛型 EventHandler 委托类型以及如何订阅事件并创建事件处理程序方法,请参阅如何发布符合 .NET 准则的事件。

C#

复制

public class SampleEventArgs
{
    public SampleEventArgs(string text) { Text = text; }
    public string Text { get; } // readonly
}

public class Publisher
{
    // Declare the delegate (if using non-generic pattern).
    public delegate void SampleEventHandler(object sender, SampleEventArgs e);

    // Declare the event.
    public event SampleEventHandler SampleEvent;

    // Wrap the event in a protected virtual method
    // to enable derived classes to raise the event.
    protected virtual void RaiseSampleEvent()
    {
        // Raise the event in a thread-safe manner using the ?. operator.
        SampleEvent?.Invoke(this, new SampleEventArgs("Hello"));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值