从属性生成的方法中检索自定义属性

本文关键字:检索 自定义属性 方法 从属性 | 更新日期: 2023-09-27 17:55:36

Inside DynamicProxy Interceptor Method 我有:

public void Intercept(IInvocation invocation)
    {
        var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);

我这样装饰我的财产:

[OneToMany(typeof(Address), "IdUser")]
public virtual IList<Address> Addresses { get; set; }

_attribute总是null.

我认为问题是invocation.Method是自动生成的get_Addresses而不是装饰的原始属性。

在这种情况下,是否有检索属性列表的解决方法?

从属性生成的方法中检索自定义属性

你是对的 - invocation.Method将是属性访问器,而不是属性。

下面是一个实用工具方法,用于查找与其访问器方法之一对应的PropertyInfo

public static PropertyInfo PropertyInfoFromAccessor(MethodInfo accessor)
{
   PropertyInfo result = null;
   if (accessor != null && accessor.IsSpecialName)
   {
      string propertyName = accessor.Name;
      if (propertyName != null && propertyName.Length >= 5)
      {
         Type[] parameterTypes;
         Type returnType = accessor.ReturnType;
         ParameterInfo[] parameters = accessor.GetParameters();
         int parameterCount = (parameters == null ? 0 : parameters.Length);
         if (returnType == typeof(void))
         {
            if (parameterCount == 0)
            {
               returnType = null;
            }
            else
            {
               parameterCount--;
               returnType = parameters[parameterCount].ParameterType;
            }
         }
         if (returnType != null)
         {
            parameterTypes = new Type[parameterCount];
            for (int index = 0; index < parameterTypes.Length; index++)
            {
               parameterTypes[index] = parameters[index].ParameterType;
            }
            try
            {
               result = accessor.DeclaringType.GetProperty(
                  propertyName.Substring(4),
                  returnType,
                  parameterTypes);
            }
            catch (AmbiguousMatchException)
            {
            }
         }
      }
   }
   return result;
}

使用此方法,您的代码将变为:

var _attribute = Attribute.GetCustomAttribute(invocation.Method, typeof(OneToManyAttribute), true);
if (_attribute == null && invocation.Method.IsSpecialName)
{
   var property = PropertyInfoFromAccessor(invocation.Method);
   if (property != null)
   {
      _attribute = Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);
   }
}

如果OneToManyAttribute仅适用于属性,不适用于方法,则可以省略对GetCustomAttribute的第一次调用:

var property = PropertyInfoFromAccessor(invocation.Method);
var _attribute = (property == null) ? null : Attribute.GetCustomAttribute(property, typeof(OneToManyAttribute), true);