AScript之事件处理脚本

AScript是一个开源的C#动态脚本解析执行引擎,脚本中支持定义事件处理。

一、Lambda委托

复制代码
 1 var s = @"
 2 var p = new Person('tom', 20);
 3 p.Saying += (ss,ee)=>{
 4     (ss as Person).Age+=1;
 5 }
 6 p.SayHello();
 7 ";
 8 var script = new Script();
 9 script.Context.AddType<Person>();
10 Assert.AreEqual("Hello, my name is tom, I'm 21 years old", script.Eval(s));

直接添加Lambda委托事件,该方式无法移除事件处理。

二、方法委托

复制代码
 1 var s = @"
 2 void saying(object sender, EventArgs e) {
 3     (sender as Person).Age+=1;
 4 }
 5 var p = new Person('tom', 20);
 6 p.Saying += saying;
 7 p.SayHello();
 8 // 可以在脚本中移除事件处理
 9 // p.Saying -= saying;
10 ";
11 var script = new Script();
12 script.Context.AddType<Person>();
13 Assert.AreEqual("Hello, my name is tom, I'm 21 years old", script.Eval(s));
14 // 外部调用触发事件
15 var p = script.Eval<Person>("p");
16 Assert.AreEqual("Hello, my name is tom, I'm 22 years old", p.SayHello());
17 // 外部移除事件处理
18 var handle = script.Context.GetEvent<EventHandler<EventArgs>>("saying");
19 p.Saying -= handle;
20 Assert.AreEqual("Hello, my name is tom, I'm 22 years old", p.SayHello());

添加方法委托事件处理,该方式可以在脚本中移除事件处理,也可以外部移除,灵活控制。

结束语

通过引入事件处理,为动态脚本增加了强大的扩展能力,比如在窗体应用动态脚本中添加控件事件处理,为程序实现更多的动态扩展能力。

AScript开源地址:https://gitee.com/rockey627/AScript

相关推荐
用户7884773163415 小时前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船20 小时前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
Jeff-Tsai21 小时前
Day 19:定制层的范围与叠加粒度
.net·架构设计·erp·definition-driven
用户3721574261352 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船2 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
Jeff-Tsai2 天前
Day 18:错误契约与用户可见消息
.net·架构设计·erp·definition-driven
IT规划师2 天前
HybridCache-缓存架构决策框架落地
架构·.net
Jeff-Tsai3 天前
Day 17:Connector 与调用端的职责收敛
.net·架构设计·erp·definition-driven
huaqianzkh3 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#
用户3721574261354 天前
C# 实现 Excel 单元格保护:锁定公式并允许编辑指定区域
c#·ai编程·编程语言