新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#中怎么自定义属性,c#中怎么自定义函数

发布时间:2024-04-25 18:15:45

C#中怎样自定义属性

在C#中可以自定义属性,可以通过以下步骤实现:

  1. 创建一个类,定义属性的名称和类型。
public class CustomAttribute : Attribute
{
    public string Name { get; set; }
    public int Age { get; set; }

    public CustomAttribute(string name, int age)
    {
        Name = name;
        Age = age;
    }
}
  1. 在需要使用属性的地方,使用自定义属性。
[CustomAttribute("John", 30)]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

  1. 使用反射获得自定义属性的值。
var customAttribute = typeof(Person).GetCustomAttributes(typeof(CustomAttribute), false).FirstOrDefault() as CustomAttribute;

if (customAttribute != null)
{
    Console.WriteLine($"Name: {customAttribute.Name}, Age: {customAttribute.Age}");
}

这样就能够定义和使用自定义属性了。