通过扩展方法获取类或方法上的成员变量(字段、属性)上的特性,获取类或方法上的特性。
扩展方法
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
public class CustomAttribute : Attribute
{
public string Name {
get; }
public int Version {
get; }
public CustomAttribute(string name, int version)
{
Name = name;
Version = version;
}
}
public static class AttributeExtensions
{
// 获取类型上的特性值
public static CustomAttribute GetCustomAttributeValue(this Type type)
{
if (type == null) throw new ArgumentNullException(nameof(type));
return (CustomAttribute)Attribute.GetCustomAttribute(type, typeof(CustomAttribute))
?? DefaultCustomAttribute();
}
// 获取方法上的特性值
public static