0

DynamicProxyInterceptorメソッドの内部には次のものがあります。

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アクセサ メソッドの 1 つに対応するを見つけるためのユーティリティ メソッドを次に示します。

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 に答える