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}");
}
}
}
定义自定义属性:
AttributeUsage
特性来指定自定义属性的应用范围(如类、方法等),以及是否可以继承和允许多个实例。MyCustomAttribute
是一个自定义特性,它接受一个字符串参数,并将其存储在私有字段 _description
中。使用自定义属性:
MyClass
类和 MyMethod
方法上应用了 MyCustom
属性,并传递了描述性的字符串。获取并显示属性信息:
GetCustomAttributes
和 GetMethod
) 来获取类和方法上的自定义属性,并输出其描述信息。通过这种方式,可以在代码中添加元数据,并在运行时通过反射访问这些元数据。
上一篇:c# 构造函数
下一篇:c# while
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站