C#中怎么自定义属性

   2024-10-20 8070
核心提示:在C#中可以自定义属性,可以通过以下步骤实现:创建一个类,定义属性的名称和类型。public class CustomAttribute : Attribute{p

在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}");}

这样就可以定义和使用自定义属性了。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号