using System;
using System.Reflection;
// 定义自定义特性
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Description { get; set; }
public MyCustomAttribute(string description)
{
Description = description;
}
}
// 使用自定义特性标记类
[MyCustom("This is a marked class")]
public class MarkedClass
{
// 使用自定义特性标记方法
[MyCustom("This is a marked method")]
public void MarkedMethod()
{
Console.WriteLine("This is the marked method.");
}
}
class Program
{
static void Main()
{
// 获取类的类型
Type type = typeof(MarkedClass);
// 获取类上的特性
object[] classAttributes = type.GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attr in classAttributes)
{
Console.WriteLine($"Class Attribute: {attr.Description}");
}
// 获取方法信息
MethodInfo methodInfo = type.GetMethod("MarkedMethod");
// 获取方法上的特性
object[] methodAttributes = methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), false);
foreach (MyCustomAttribute attr in methodAttributes)
{
Console.WriteLine($"Method Attribute: {attr.Description}");
}
// 根据不同标记执行不同逻辑
if (classAttributes.Length > 0)
{
Console.WriteLine("Execute class - related logic based on the class attribute.");
}
if (methodAttributes.Length > 0)
{
Console.WriteLine("Execute method - related logic based on the method attribute.");
}
}
}
- 定义自定义特性:
- 创建了一个
MyCustomAttribute
类,继承自Attribute
,并使用AttributeUsage
指定该特性可以应用于类和方法。它有一个Description
属性用于存储描述信息。
- 使用特性标记类和方法:
- 在
MarkedClass
类上使用[MyCustom("This is a marked class")]
标记,在MarkedMethod
方法上使用[MyCustom("This is a marked method")]
标记。
- 使用反射获取标记信息:
- 使用
Type.GetCustomAttributes
方法获取类上的特性。
- 使用
MethodInfo.GetCustomAttributes
方法获取方法上的特性。
- 根据标记执行不同逻辑:
- 通过判断获取到的特性数组长度,执行不同的逻辑。例如当类上有特性时,执行类相关逻辑;当方法上有特性时,执行方法相关逻辑。