C#内置委托:Action、Func、Predicate
|
admin
2025年3月20日 23:46
本文热度 1731
|
Action:传递没有参数没有返回值的函数
Func:传递有参数有返回值的函数
Predicate:可接收参数,返回值类型为bool
创建一个Class1类,编写测试函数
namespace _002_内置委托{ internal class Class1 { public void T1() { MessageBox.Show("测试1"); } public void T2() { MessageBox.Show("测试2"); } public int T3(int a, int b) { return a + b; } public int T4(int a, int b) { return a - b; } public bool T5(int a) { if (a % 4 == 0 && a % 100 != 0) { return true; } else { return false; } } }}
namespace _002_内置委托{ public partial class 内置委托 : Form { public 内置委托() { InitializeComponent(); } private void btAction_Click(object sender, EventArgs e) { Class1 class1 = new Class1(); Action action1 = new Action(class1.T1); Action action2 = new Action(class1.T2); action1.Invoke(); action2.Invoke(); } private void btFunc_Click(object sender, EventArgs e) { Class1 class1 = new Class1(); Func<int, int, int> func1 = new Func<int, int, int>(class1.T3); int res1 = func1.Invoke(1, 2); MessageBox.Show(res1.ToString()); } private void btPredicate_Click(object sender, EventArgs e) { Class1 class1 = new Class1(); Predicate<int> predicate = new Predicate<int>(class1.T5); bool res1 = predicate.Invoke(2023); MessageBox.Show(res1.ToString()); } }}
阅读原文:原文链接
该文章在 2025/3/21 10:16:51 编辑过