MST

星途 面试题库

面试题:C# 元编程中特性(Attribute)与反射的结合使用

在C#元编程中,特性(Attribute)常常与反射配合使用。请编写一段代码,通过自定义特性标记类和类中的方法,然后使用反射来获取这些标记信息,并根据不同的标记执行不同的逻辑。
40.6万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
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.");
        }
    }
}
  1. 定义自定义特性
    • 创建了一个MyCustomAttribute类,继承自Attribute,并使用AttributeUsage指定该特性可以应用于类和方法。它有一个Description属性用于存储描述信息。
  2. 使用特性标记类和方法
    • MarkedClass类上使用[MyCustom("This is a marked class")]标记,在MarkedMethod方法上使用[MyCustom("This is a marked method")]标记。
  3. 使用反射获取标记信息
    • 使用Type.GetCustomAttributes方法获取类上的特性。
    • 使用MethodInfo.GetCustomAttributes方法获取方法上的特性。
  4. 根据标记执行不同逻辑
    • 通过判断获取到的特性数组长度,执行不同的逻辑。例如当类上有特性时,执行类相关逻辑;当方法上有特性时,执行方法相关逻辑。