A variable declared outside the anonymous method can be accessed inside the anonymous method. ตัวแปรที่ประกาศไว้ภายนอก anonymous method สามารถเข้าถึงได้ภายในเมธอด
A variable declared inside the anonymous method can’t be accessed outside the anonymous method. ตัวแปรที่ประกาศไว้ภายใน anonymous method ไม่สามารถเข้าถึงได้จากภายนอกเมธอด
ตัวอย่าง
//สร้าง delegate ชื่อ del สำหรับเมธอดที่รับ int สองค่าและคืนค่าเป็น int
delegate int del(int x, int y);
static void Main(string[] args)
{
//สร้าง Anonymous Method โดยใช้ delegate keyword ไม่จำเป็นต้องมีชื่อเมธอด
del d1 = delegate(int x, int y)
{
return x * y;
};
//เรียกใช้ Anonymous Method ผ่าน delegate d1
int z1 = d1(2, 3);
Console.WriteLine(z1); //Output: 6 (ผลลัพธ์จาก x * y(2, 3))
}
using System;
using System.Threading;
class AnonymouseMothod
{
//สร้าง delegate ชื่อ MeDelegate ซึ่งไม่ได้รับพารามิเตอร์ใดๆ และคืนค่าเป็น void
delegate void MeDelegate();
static void Main(string[] args)
{
//basic anomymous method > สร้าง Anonymous Method โดยใช้คำว่า delegate
//โดยไม่มีการระบุพารามิเตอร์ (เพราะ MeDelegate ไม่ได้กำหนดพารามิเตอร์)
MeDelegate de = delegate
{
Console.WriteLine("Anonymouse is invoked.");
};
de(); //เรียกใช้ Anonymous Method ผ่าน delegate de ทำให้ข้อความแสดงออกมาทางคอนโซล
//basic anomymous method with thread
//สร้าง Anonymous Method อีกครั้ง แต่อันนี้ใช้สำหรับทำงานร่วมกับ Thread
Thread t = new Thread(new ThreadStart(delegate
{
Console.WriteLine("Anonymouse method in thread.");
}));
t.Start(); //เริ่มการทำงานของ thread ซึ่งทำให้ข้อความถูกพิมพ์ออกมาภายใน thread ใหม่
}
}
//ตัวอย่าง Anonymous Class ที่มีการสร้างฟังก์ชันแบบไม่มีชื่อ
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous Method in Java");
}
};
new Thread(r).start();
//ตัวอย่าง Lambda Expression
Runnable r = () -> System.out.println("Lambda Expression in Java");
new Thread(r).start();
#include <stdio.h>
//ฟังก์ชันปกติที่ถูกส่งไปยังฟังก์ชันอื่น
void printMessage() {
printf("Anonymous-like function in C\n");
}
void execute(void (*func)()) {
func();
}
int main() {
//ส่งฟังก์ชันปกติผ่าน function pointer
execute(printMessage);
return 0;
}
//ตัวอย่างการใช้นิพจน์ lambda เพื่อส่งคืนฟังก์ชัน
>>>def make_incrementor(n):
... return lambda x: x + n
...
>>>f = make_incrementor(42)
>>>f(0)
42
>>>f(1)
43