// 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}");
}
}
}
定义自定义特性:
MyCustomAttribute 是一个自定义特性,它继承自 Attribute 类,并包含一个构造函数和一个属性 Description。使用特性:
[MyCustom("描述")] 语法可以将特性应用到类、方法或属性上。例如,ExampleClass 类被标记为 [MyCustom("这是一个示例类")]。获取并显示特性信息:
Main 方法中,通过反射 (Reflection) 获取类、方法和属性上的特性,并输出它们的描述信息。GetCustomAttributes 方法用于检索指定类型的特性。这个示例展示了如何定义、应用和读取 C# 中的自定义特性。
上一篇:c#枚举
下一篇:c#二维数组
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站