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

วิธีใช้ Attributes ใน C#

Attribute คือแท็กประกาศ (declarative tag) ใช้สื่อข้อมูลให้ Runtime เกี่ยวกับพฤติกรรมของสมาชิกต่างๆ เช่น คลาส เมธอด โครงสร้าง Enum Assembly เป็นต้น วางไว้เหนือสมาชิกในวงเล็บเหลี่ยม [ ]

ไวยากรณ์:

[attribute(positional_parameters, name_parameter = value, ...)] Element

.NET มี 2 ประเภท: Pre-defined attributes และ Custom attributes

ตัวอย่าง Custom Attribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
public class DeBugInfo : System.Attribute