简明C#事件

本文通过一个简单的示例解释了C#中的事件概念及其使用方法。包括如何声明回调原型、定义事件、触发事件以及如何挂接回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#事件:就是一个针对对象的可挂接回调函数。
1、声明回调原形,必须为 delegate .....XXXX();
2、在要添加事件的类中,声明事件。
3、在类中选择一个触发事件的时机。触发事件前,一定要先判断事件是否为空!
4、挂接事件。

None.gifusing System;
None.gif
public delegate void ChangeEvent();     //1、回调函数的原形
None.gif

None.gif
class myClass
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
public event ChangeEvent change;    //2、声明事件
InBlock.gif
    int _id;
InBlock.gif    
public int ID
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
get dot.gifreturn _id; }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
set dot.gif
InBlock.gif            
if ((1 == value) && (change != null))
InBlock.gif                change();               
//3、触发事件。触发事件之前,先要判断事件是否已实例化的(取上面的change != null);
InBlock.gif
            _id = value; 
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
None.gif
class Test
ExpandedBlockStart.gifContractedBlock.gif
dot.gif{
InBlock.gif    
static void Main()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        myClass c 
= new myClass();
InBlock.gif        
//4、c对象有一个事件change,下句是添加回调函数实例。
InBlock.gif
        c.change += new ChangeEvent(new Test().Ah);
InBlock.gif        c.change 
+= new ChangeEvent(yiyi);
InBlock.gif        c.ID 
= 1;                       
InBlock.gif        Console.Write(
"c.ID :{0}", c.ID);
ExpandedSubBlockEnd.gif    }

InBlock.gif    
static void yiyi()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif
InBlock.gif        Console.Write(
"yiyi!!\n");
ExpandedSubBlockEnd.gif    }

InBlock.gif    
void Ah()
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        Console.Write(
"Ah!\n");
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}
  在网上查找一些关于事件的说明,头都看大了,自已写一个简单的说明。
  够用就行了,不要死拘语法,用一些基本的, 解决问题的方法就行。
  最后一句说,C#事件,就是一个针对对象的可挂接回调函数。

转载于:https://www.cnblogs.com/freebird92/archive/2006/12/28/606215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值