
C#中Attribute的使用方法详解
5星
- 浏览量: 0
- 大小:None
- 文件类型:PDF
简介:
本文详细介绍了在C#编程语言中如何使用Attribute来扩展元数据信息,包括其定义、常用类型和应用实例。适合中级开发者参考学习。
C#属性是一种元数据形式,用于向编译器、运行环境或工具提供额外的信息。它们可以附加到代码的不同元素上,例如类、方法、字段等,并实现特定功能如注释、序列化及验证等。
一、属性的运用范围
1. **程序集**:整个程序集的相关元数据。
2. **模块**:编译单元,通常对应于一个.cs文件。
3. **类型**:包括类、结构体、枚举和接口。
4. **字段**:类中的变量。
5. **方法**:包含构造函数及普通的方法。
6. **参数**:输入或输出的参数
7. **返回值**:从方法中返回的数据。
8. **属性(property)**: 类中的getter和setter。
以下是一个使用自定义属性`TestAttribute`的例子:
```csharp
[TestAttribute]
public class TestClass
{
[TestAttribute]
private string _testField;
[TestAttribute]
public string TestProperty { get; set; }
[TestAttribute]
[return: TestAttribute]
public string TestMethod([TestAttribute] string testParam)
{
throw new NotImplementedException();
}
}
```
二、自定义属性
创建自定义属性时,需要继承`System.Attribute`基类。下面是一个名为`StringLengthAttribute`的示例,用于限制字符串属性的最大长度:
```csharp
[AttributeUsage(AttributeTargets.Property)]
public class StringLengthAttribute : Attribute
{
private int _maximumLength;
public StringLengthAttribute(int maximumLength)
{
_maximumLength = maximumLength;
}
public int MaximumLength => _maximumLength;
}
```
`AttributeUsage`属性用于指定自定义属性可以应用于哪些元素。在这个例子中,`StringLengthAttribute`只能应用于属性。
然后可以在类中使用该自定义属性来约束字段:
```csharp
public class People
{
[StringLength(8)]
public string Name { get; set; }
[StringLength(15)]
public string Description { get; set; }
}
```
接下来,可以创建一个验证类以检查这些属性是否符合限制条件:
```csharp
public class ValidationModel
{
public void Validate(object obj)
{
var t = obj.GetType();
var properties = t.GetProperties();
foreach (var property in properties)
{
if (!property.IsDefined(typeof(StringLengthAttribute), false))
continue;
var attributes = property.GetCustomAttributes(false);
var stringLengthAttr = attributes.OfType
全部评论 (0)


