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

相关推荐
李高钢18 小时前
C# WinForms 架构与项目实战:多窗体通信、三层架构、数据库、日志与配置
架构·c#·winforms
OPEN-F21 小时前
Python进阶教程:自动化办公实战
python·c#·自动化
码农刚子1 天前
用 .NET 8 + uni-app 做一套多租户畜牧 SaaS:我们在秦巴牧云踩过的 6 个坑
uni-app·.net·saas
czhc11400756631 天前
C# 处理体数据:装、钉、交、取消
c#
淡海水1 天前
03-03-线性-LinkedList-T-源码不变式与选择边界
windows·链表·c#·编译·linkedlist·clr·机器码
longxiaozhang62 天前
C# Array类:数组其实没那么难
开发语言·c#
longxiaozhang62 天前
C#运算符重载:让对象也能使用“加减乘除”
开发语言·c#
花落人散处2 天前
C# 核心编程知识点总结:网络编程、委托与事件、异步编程与LINQ
c#
fl1768312 天前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
CoderIsArt2 天前
OPC UA 完整介绍、官网、C# 简单使用
开发语言·c#