从属性生成的方法中检索CustomAttribute

时间:2013-01-23 16:12:40

标签: c# castle-dynamicproxy

在DynamicProxy Interceptor方法中我有:

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而不是装饰的原始属性。

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

1 个答案:

答案 0 :(得分:1)

你是对的 - 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);
相关问题