Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# attribute

作者:氵冗氵孚   发布日期:2025-09-27   浏览:52

using System;

// 定义一个自定义属性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class MyCustomAttribute : Attribute
{
    private string _description;

    public MyCustomAttribute(string description)
    {
        _description = description;
    }

    public string Description
    {
        get { return _description; }
    }
}

// 使用自定义属性
[MyCustom("这是一个示例类")]
public class MyClass
{
    [MyCustom("这是一个示例方法")]
    public void MyMethod()
    {
        Console.WriteLine("Hello, World!");
    }
}

// 获取并显示属性信息
class Program
{
    static void Main()
    {
        var myClassType = typeof(MyClass);
        var classAttributes = myClassType.GetCustomAttributes(typeof(MyCustomAttribute), false);

        foreach (MyCustomAttribute attr in classAttributes)
        {
            Console.WriteLine($"类的描述: {attr.Description}");
        }

        var methodInfo = myClassType.GetMethod("MyMethod");
        var methodAttributes = methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), false);

        foreach (MyCustomAttribute attr in methodAttributes)
        {
            Console.WriteLine($"方法的描述: {attr.Description}");
        }
    }
}

解释说明

  1. 定义自定义属性:

    • 使用 AttributeUsage 特性来指定自定义属性的应用范围(如类、方法等),以及是否可以继承和允许多个实例。
    • MyCustomAttribute 是一个自定义特性,它接受一个字符串参数,并将其存储在私有字段 _description 中。
  2. 使用自定义属性:

    • MyClass 类和 MyMethod 方法上应用了 MyCustom 属性,并传递了描述性的字符串。
  3. 获取并显示属性信息:

    • 使用反射 (GetCustomAttributesGetMethod) 来获取类和方法上的自定义属性,并输出其描述信息。

通过这种方式,可以在代码中添加元数据,并在运行时通过反射访问这些元数据。

上一篇:c# 构造函数

下一篇:c# while

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

c# rectangle

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站