在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}");
}
这样就可以定义和使用自定义属性了。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:C#中如何自定义元数据属性