面试题答案
一键面试- 定义自定义特性:
- 首先创建一个继承自
System.Attribute
的类。例如:
public class MyCustomAttribute : System.Attribute { public string Description { get; set; } public MyCustomAttribute(string description) { Description = description; } }
- 首先创建一个继承自
- 在方法参数上使用自定义特性:
- 在定义方法时,在参数前面使用自定义特性。例如:
public void MyMethod([MyCustom("This is a parameter with custom attribute")] int param) { // 方法实现 }
- 应用场景举例:
- 参数验证:假设我们有一个方法用于处理用户输入的年龄。可以定义一个自定义特性来验证年龄是否在合理范围内。
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
特性,该特性用于定义年龄的合理范围。在方法内部,可以通过反射获取特性并进行参数验证。