ภาพรวม
nameof เป็น operator ที่คืนค่า ชื่อของตัวแปร ประเภท หรือสมาชิก เป็นสตริง literal ตรวจสอบได้ตอน compile-time ช่วย refactoring ได้ปลอดภัย
รูปแบบการใช้งาน
var vehicle = "motorbike"; Console.WriteLine(nameof(vehicle)); // "vehicle" (ชื่อตัวแปร ไม่ใช่ค่า)
ตัวอย่างโค้ดเต็ม
using System;
public class Program
{
static void Main()
{
var vehicle = "motorbike";
Console.WriteLine(nameof(vehicle)); // vehicle
var time = DateTime.Now.ToLocalTime();
Console.WriteLine(nameof(time)); // time
var a = false;
Console.WriteLine(nameof(a)); // a
}
}
ผลลัพธ์
vehicle time a
กรณีใช้งานที่ดี
- โยน Exception:
throw new ArgumentNullException(nameof(param)); - INotifyPropertyChanged:
OnPropertyChanged(nameof(MyProperty)); - Logging/Debugging:
Log(nameof(MyMethod)); - MVC:
RedirectToAction(nameof(HomeController.Index))
ข้อดี
- Refactor-safe: เปลี่ยนชื่อตัวแปร/เมธอด → nameof อัปเดตอัตโนมัติ
- Compile-time checking: ไม่มี typo ได้
- No runtime overhead: เป็น constant string literal