Question

Je suis en train d'accéder à un attribut personnalisé appliqué à une méthode dans un intercepteur du château, par exemple:.

[MyCustomAttribute(SomeParam = "attributeValue")]
public virtual MyEntity Entity { get; set; }

en utilisant le code suivant:

internal class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method.GetCustomAttributes(typeof(MyCustomAttribute), true) != null)
        {
            //Do something
        }
    }
}

L'intercepteur est mise à feu OK lorsque la méthode est appelée, mais ce code ne renvoie pas l'attribut personnalisé. Comment puis-je y parvenir?

Était-ce utile?

La solution 3

Je pense que je l'ai pensé à elle - c'est à cause de la différence entre la propriété et la méthode. Il est la méthode get_ qui déclenche l'intercepteur, et ce n'est pas décoré avec l'attribut de la propriété parent.

Autres conseils

Essayez la méthode statique Attribute.GetCustomAttribute(...) pour cela. Il est bizarre, mais ces deux méthodes renvoient parfois des résultats différents pour une raison étrange.

Essayez

private static Attribute getMyCustomAttribute(IInvocation invocation)
{
   var methodInfo = invocation.MethodInvocationTarget;
   if (methodInfo == null)
   {
      methodInfo = invocation.Method;
   }
   return Attribute.GetCustomAttribute(methodInfo, typeof(MyCustomAttribute), true);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top