.net 获取属性的自定义特性
时间: 2024-03-13 15:47:47 浏览: 22
在 .NET 中,除了使用内置的属性修饰符之外,我们还可以创建自定义的特性(Attribute)来为属性添加元数据。这些自定义特性可以通过继承 System.Attribute 类来定义,并且可以在属性上使用 [AttributeName] 的形式进行标记。
以下是一个简单的示例,展示如何定义和使用自定义特性:
```
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string Description { get; set; }
public MyAttribute(string description)
{
Description = description;
}
}
public class MyClass
{
[MyAttribute("This is my property")]
public int MyProperty { get; set; }
}
```
在这个示例中,我们定义了一个名为 MyAttribute 的自定义特性,并将它标记为只能用于属性。然后,我们定义了一个 MyClass 类,并为它的 MyProperty 属性添加了 MyAttribute 特性。
现在,我们可以使用反射来获取 MyProperty 属性的 MyAttribute 特性,并访问它的属性值。例如:
```
var propertyInfo = typeof(MyClass).GetProperty("MyProperty");
var attribute = propertyInfo.GetCustomAttribute<MyAttribute>();
Console.WriteLine(attribute.Description);
```
这里,我们使用反射获取 MyProperty 属性的 PropertyInfo 对象,并使用 GetCustomAttribute 方法获取它的 MyAttribute 特性。然后,我们访问特性的 Description 属性,并输出它的值。
需要注意的是,我们必须指定泛型类型参数 <MyAttribute> 来告诉 GetCustomAttribute 方法要获取哪种类型的特性。如果属性上没有标记该特性,GetCustomAttribute 方法将返回 null。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)