MST

星途 面试题库

面试题:C# 特性(Attribute)在方法参数上的应用

请简述如何在C#中为方法的参数定义并使用自定义特性(Attribute),并举例说明一个可能的应用场景。
44.5万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
  1. 定义自定义特性
    • 首先创建一个继承自System.Attribute的类。例如:
    public class MyCustomAttribute : System.Attribute
    {
        public string Description { get; set; }
        public MyCustomAttribute(string description)
        {
            Description = description;
        }
    }
    
  2. 在方法参数上使用自定义特性
    • 在定义方法时,在参数前面使用自定义特性。例如:
    public void MyMethod([MyCustom("This is a parameter with custom attribute")] int param)
    {
        // 方法实现
    }
    
  3. 应用场景举例
    • 参数验证:假设我们有一个方法用于处理用户输入的年龄。可以定义一个自定义特性来验证年龄是否在合理范围内。
    public class AgeRangeAttribute : System.Attribute
    {
        public int MinAge { get; set; }
        public int MaxAge { get; set; }
        public AgeRangeAttribute(int minAge, int maxAge)
        {
            MinAge = minAge;
            MaxAge = maxAge;
        }
    }
    
    public void ProcessAge([AgeRange(18, 100)] int age)
    {
        if (age < ((AgeRangeAttribute)Attribute.GetCustomAttribute(
            typeof(ProcessAge).GetParameters()[0], typeof(AgeRangeAttribute))).MinAge
            || age > ((AgeRangeAttribute)Attribute.GetCustomAttribute(
                typeof(ProcessAge).GetParameters()[0], typeof(AgeRangeAttribute))).MaxAge)
        {
            throw new ArgumentException("Age is out of range.");
        }
        // 处理年龄的逻辑
    }
    
    • 在上述例子中,ProcessAge方法的age参数使用了AgeRangeAttribute特性,该特性用于定义年龄的合理范围。在方法内部,可以通过反射获取特性并进行参数验证。