在C#中可以自定義屬性,可以通過以下步驟實現:
public class CustomAttribute : Attribute
{
public string Name { get; set; }
public int Age { get; set; }
public CustomAttribute(string name, int age)
{
Name = name;
Age = age;
}
}
[CustomAttribute("John", 30)]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
var customAttribute = typeof(Person).GetCustomAttributes(typeof(CustomAttribute), false).FirstOrDefault() as CustomAttribute;
if (customAttribute != null)
{
Console.WriteLine($"Name: {customAttribute.Name}, Age: {customAttribute.Age}");
}
這樣就可以定義和使用自定義屬性了。