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

c# 特性

作者:枫尘于往逝   发布日期:2026-05-16   浏览:125

// C# 特性 (Attributes) 示例

// 定义一个自定义特性
public class MyCustomAttribute : Attribute
{
    public string Description { get; }

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

// 使用特性标记类、方法或属性
[MyCustom("这是一个示例类")]
public class ExampleClass
{
    [MyCustom("这是一个示例方法")]
    public void ExampleMethod()
    {
        Console.WriteLine("这是示例方法的实现");
    }

    [MyCustom("这是一个示例属性")]
    public string ExampleProperty { get; set; }
}

// 获取并显示特性信息
class Program
{
    static void Main()
    {
        var type = typeof(ExampleClass);
        var customAttribute = type.GetCustomAttributes(typeof(MyCustomAttribute), false).FirstOrDefault() as MyCustomAttribute;

        if (customAttribute != null)
        {
            Console.WriteLine($"类描述: {customAttribute.Description}");
        }

        var methodInfo = type.GetMethod("ExampleMethod");
        var methodAttribute = methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), false).FirstOrDefault() as MyCustomAttribute;

        if (methodAttribute != null)
        {
            Console.WriteLine($"方法描述: {methodAttribute.Description}");
        }

        var propertyInfo = type.GetProperty("ExampleProperty");
        var propertyAttribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), false).FirstOrDefault() as MyCustomAttribute;

        if (propertyAttribute != null)
        {
            Console.WriteLine($"属性描述: {propertyAttribute.Description}");
        }
    }
}

解释说明:

  1. 定义自定义特性

    • MyCustomAttribute 是一个自定义特性,它继承自 Attribute 类,并包含一个构造函数和一个属性 Description
  2. 使用特性

    • 使用 [MyCustom("描述")] 语法可以将特性应用到类、方法或属性上。例如,ExampleClass 类被标记为 [MyCustom("这是一个示例类")]
  3. 获取并显示特性信息

    • Main 方法中,通过反射 (Reflection) 获取类、方法和属性上的特性,并输出它们的描述信息。GetCustomAttributes 方法用于检索指定类型的特性。

这个示例展示了如何定义、应用和读取 C# 中的自定义特性。

上一篇:c#枚举

下一篇:c#二维数组

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

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

Laravel 中文站