Java ใช้ @FunctionalInterface (Single Abstract Method - SAM) สำหรับ Lambda Expression ใน C# ใช้ Delegate ซึ่งเป็น First-class Citizen ตั้งแต่ Version 1.0
Java Functional Interface
// Java
@FunctionalInterface
public interface MyInterface {
void invoke();
}
public class Demo {
void method() {
MyInterface x = () -> MyFunc();
x.invoke();
}
void MyFunc() { }
}
C# Delegate (Equivalent)
// C# - Delegate Declaration
public delegate void MyDelegate();
public class Demo
{
public void Method()
{
// Lambda Expression assigned to Delegate
MyDelegate d = () => MyFunc();
d(); // Invoke
}
public void MyFunc() { }
}
Built-in Delegate Types (ไม่ต้องประกาศเอง)
| Delegate | Signature | ใช้สำหรับ |
|---|---|---|
Action | void () | Method ไม่มี Parameter ไม่มี Return |
Action<T> | void (T) | 1 Parameter, No Return |
Action<T1,T2> | void (T1, T2) | 2 Parameters, No Return |
Func<TResult> | TResult () | No Parameter, Has Return |
Func<T, TResult> | TResult (T) | 1 Parameter, Has Return |
Func<T1,T2,TResult> | TResult (T1, T2) | 2 Parameters, Has Return |
Predicate<T> | bool (T) | Condition Check (Return bool) |
ตัวอย่างใช้ Built-in Delegates
using System;
public class Demo
{
// Action - No Return
public void Process(Action logger)
{
logger("Processing started");
// ... work ...
logger("Processing completed");
}
// Func - Has Return
public T Transform(T input, Func transformer)
{
return transformer(input);
}
// Predicate - Condition
public List Filter(List numbers, Predicate condition)
{
var result = new List();
foreach (var n in numbers)
if (condition(n)) result.Add(n);
return result;
}
public static void Main()
{
var demo = new Demo();
// Lambda with Action
demo.Process(msg => Console.WriteLine($"[LOG] {msg}"));
// Lambda with Func
int doubled = demo.Transform(5, x => x * 2); // 10
// Lambda with Predicate
var evens = demo.Filter(new List { 1, 2, 3, 4, 5 }, x => x % 2 == 0); // {2, 4}
}
}
Multicast Delegate (Delegate Chaining)
Action action1 = () => Console.WriteLine("First");
Action action2 = () => Console.WriteLine("Second");
Action combined = action1 + action2;
combined(); // Prints both
// Event Pattern (Built-in Multicast)
public event EventHandler MyEvent;
Method Group Conversion
// แทน Lambda ใช้ Method Group ได้
Func add = (a, b) => a + b;
Func add2 = Math.Add; // Static Method
// Instance Method
var list = new List();
Action addToList = list.Add; // Method Group Conversion
เปรียบเทียบ
| ด้าน | Java Functional Interface | C# Delegate |
|---|---|---|
| Declaration | Interface + @FunctionalInterface | delegate keyword หรือ Built-in |
| Lambda Syntax | () -> expr | () => expr |
| Method Reference | Class::method | Class.Method (Method Group) |
| Multicast | ไม่รองรับโดยตรง | รองรับ (+=, -=) |
| Closure Capture | Effectively Final Variables | Variables (Mutable Capture) |
สรุป
C# Delegate ทรงพลังกว่า Java Functional Interface: รองรับ Multicast, Method Group Conversion, Closure ที่ยืดหยุ่นกว่า และมี Built-in Types (Action/Func/Predicate) ครบครัน