C#特性(Attribute)用法实例解析

夏知夏
夏知夏
发布时间:2026-10-14| 2人浏览过
原创

C#中的特性(Attribute)是一种强大的元数据存储机制,广泛应用于程序集、类型、成员等元素上。本文将详细讲解如何运用特性,并演示如何通过继承Attribute类来自定义特性,结合反射技术实现运行时逻辑验证,如字符串长度校验。

特性的应用范围

在C#程序中,特性可以应用于多种目标元素。除了程序集和模块外,常见的应用位置包括:

  • 类型:如类(Class)、结构体(Struct)、枚举(Enum)、接口(Interface)和委托(Delegate)
  • 成员:字段(Field)、属性(Property)
  • 方法:构造函数、普通方法及其返回值
  • 参数:方法的输入参数

第1步:定义通用特性示例

首先,创建一个基础的特性类,展示其在不同目标上的应用方式。使用[AttributeUsage]指定该特性可用于所有目标。

[AttributeUsage(AttributeTargets.All)]
public class TestAttribute : Attribute
{
}

[TestAttribute] // 应用于结构
public struct TestStruct { }

[TestAttribute] // 应用于枚举
public enum TestEnum { }

// 应用于类及内部成员
[TestAttribute]
public class TestClass
{
    [TestAttribute]
    public TestClass() { }

    [TestAttribute] // 字段
    private string _testField;

    [TestAttribute] // 属性
    public string TestProperty { get; set; }

    // 方法、参数及返回值
    [TestAttribute]
    [return: TestAttribute]
    public string TestMethod([TestAttribute] string testParam)
    {
        throw new NotImplementedException();
    }
}

自定义特性实现步骤

为了满足公共语言规范(CLS),所有自定义特性必须继承自System.Attribute。下面通过一个“字符串长度验证”的案例,演示自定义特性的完整开发流程。

第1步:定义特性类

创建StringLengthAttribute类,继承Attribute。使用AttributeUsage限制其仅能应用于属性(Property)。设计构造函数接收最大长度参数,并通过只读属性暴露该值。

[AttributeUsage(AttributeTargets.Property)]
public class StringLengthAttribute : Attribute
{
    private int _maximumLength;

    public StringLengthAttribute(int maximumLength)
    {
        _maximumLength = maximumLength;
    }

    public int MaximumLength
    {
        get { return _maximumLength; }
    }
}

第2步:在实体类中应用特性

创建一个业务实体类People,并在其字符串属性上应用自定义特性,指定不同的长度限制。

public class People
{
    [StringLength(8)]
    public string Name { get; set; }

    [StringLength(15)]
    public string Description { get; set; }
}

第3步:编写验证逻辑

利用反射技术在运行时读取特性信息并进行验证。核心步骤包括获取类型属性、检查是否定义了特定特性、提取特性参数值以及对比实际数据。

public class ValidationModel
{
    public void Validate(object obj)
    {
        var t = obj.GetType();
        // 获取所有公共属性
        var properties = t.GetProperties();

        foreach (var property in properties)
        {
            // 检查是否存在[StringLength]特性
            if (!property.IsDefined(typeof(StringLengthAttribute), false)) 
                continue;

            var attributes = property.GetCustomAttributes();
            foreach (var attribute in attributes)
            {
                // 获取特性中定义的最大长度
                var maxinumLength = (int)attribute.GetType()
                    .GetProperty("MaximumLength")
                    .GetValue(attribute);

                // 获取当前对象的属性值
                var propertyValue = property.GetValue(obj) as string;
                
                if (propertyValue == null)
                    throw new Exception("属性值为空");

                if (propertyValue.Length > maxinumLength)
                    throw new Exception(string.Format(
                        "属性{0}的值{1}的长度超过了{2}", 
                        property.Name, propertyValue, maxinumLength));
            }
        }
    }
}

第4步:执行验证测试

在Main方法中实例化对象并触发验证。当Name字段的值超过设定的8个字符限制时,系统将抛出异常。

private static void Main(string[] args)
{
    var people = new People()
    {
        Name = "qweasdzxcasdqweasdzxc", // 长度超8
        Description = "description"
    };
    try
    {
        new ValidationModel().Validate(people);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    Console.ReadLine();
}

以上就是C#特性(Attribute)用法实例解析的详细内容,更多关于C#元数据编程的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。