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 編輯過