Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่าง Func Delegate และ Action Delegate ใน C#

ทั้งคู่เป็น Delegate ใน Namespace System แตต่างกันที่ Return Type

Func<T1, T2, ..., TResult>

  • มี Return Type (TResult)
  • Parameter 0-16 ตัว + 1 Return
  • Last Type Parameter = Return Type
Func append = (first, last) => first + last;
string fullName = append("Michael", "Jackson"); // "MichaelJackson"

Action<T1, T2, ...>

  • **ไม่มี Return Type (void)**
  • Parameter 1-16 ตัว (ไม่มี Return)
Action print = (first, last) => Console.WriteLine(first + last);
print("Michael", "Jackson"); // Output: MichaelJackson

สรุป

DelegateReturnParametersUse Case
FuncYes (TResult)0-16 In + 1 OutTransformation, Calculation, Factory
ActionNo (void)1-16 InSide Effects: Logging, Writing, Mutating

ยังมี Predicate<T> = Func<T, bool> สำหรับ Condition Check