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

การเข้าถึง Attributes และ Methods ใน C#

Attribute (แอตทริบิวต์) คืออะไร?

Attribute เป็นแท็กประกาศ (declarative tag) ที่ใช้ส่งข้อมูลเมตา (metadata) ไปยัง runtime เกี่ยวกับพฤติกรรมขององค์ประกอบต่างๆ เช่น คลาส เมธอด โครงสร้าง การนับประเภท แอสเซมบลี เป็นต้น

รูปแบบการประกาศ Attribute

[AttributeName(positional_parameters, name_parameter = value, ...)]
Element
  • ชื่อ attribute และค่าต่างๆ อยู่ภายในวงเล็บเหลี่ยม [ ]
  • Positional parameters - พารามิเตอร์ตามลำดับ
  • Named parameters - พารามิเตอร์แบบระบุชื่อ (name = value)

ตัวอย่าง: Conditional Attribute

ใช้ [Conditional("DEBUG")] เพื่อให้เมธอดทำงานเฉพาะเมื่อกำหนดค่า DEBUG

ตัวอย่างโค้ดสมบูรณ์

#define DEBUG
using System;
using System.Diagnostics;

public class Demo
{
    [Conditional("DEBUG")]
    public static void Message(string str)
    {
        Console.WriteLine(str);
    }
}

class Test
{
    static void FunctionDisplay()
    {
        Demo.Message("ฟังก์ชันของเรา...");
    }
    
    public static void Main()
    {
        Demo.Message("นี่คือฟังก์ชัน Main!");
        FunctionDisplay();
        Console.ReadKey();
    }
}

ผลลัพธ์ (เมื่อ define DEBUG)

นี่คือฟังก์ชัน Main!
ฟังก์ชันของเรา...

หมายเหตุ: หากนำ #define DEBUG ออก หรือ build แบบ Release เมธอด Message จะไม่ถูกเรียกเลย (ถูก compiler ตัดออก)

Attribute ที่พบบ่อยใน .NET

Attribute วัตถุประสงค์
[Obsolete] ทำเครื่องหมายว่าสมาชิกล้าสมัย
[Serializable] อนุญาตให้คลาสถูก serialize
[DllImport] เรียกฟังก์ชันจาก DLL ภายนอก (unmanaged code)
[DataContract]/[DataMember] สำหรับ WCF serialization
[JsonProperty] กำหนดชื่อ property ใน JSON (Newtonsoft.Json)
[Required] Validation ใน ASP.NET Core / Entity Framework

Custom Attribute (สร้าง Attribute เอง)

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class DeveloperInfoAttribute : Attribute
{
    public string Name { get; set; }
    public string Date { get; set; }
    public string Version { get; set; }
    
    public DeveloperInfoAttribute(string name)
    {
        Name = name;
    }
}

// การใช้งาน
[DeveloperInfo("สมชาย", Date = "2024-01-15", Version = "1.0")]
public class MyClass { }

การอ่าน Attribute ผ่าน Reflection

var attrs = typeof(MyClass).GetCustomAttributes(typeof(DeveloperInfoAttribute), false);
foreach (DeveloperInfoAttribute attr in attrs)
{
    Console.WriteLine($"ผู้พัฒนา: {attr.Name}, วันที่: {attr.Date}, เวอร์ชัน: {attr.Version}");
}

สรุป

  • Attribute ให้ข้อมูลเมตาเพิ่มเติมให้กับโค้ด
  • ใช้ [Conditional] สำหรับควบคุมการคอมไพล์แบบเงื่อนไข
  • สามารถสร้าง Custom Attribute ได้โดยสืบทอดจาก System.Attribute
  • อ่านค่า Attribute ได้ผ่าน Reflection ใน runtime