0

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

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

4

1 回答 1

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);
于 2013-01-23T17:08:53.277 回答