C# 从Castle Windsor拦截器访问方法的自定义属性

C# 从Castle Windsor拦截器访问方法的自定义属性,c#,castle-windsor,interceptor,castle-dynamicproxy,C#,Castle Windsor,Interceptor,Castle Dynamicproxy,我试图访问应用于castle拦截器内方法的自定义属性,例如: [MyCustomAttribute(SomeParam = "attributeValue")] public virtual MyEntity Entity { get; set; } 使用以下代码: internal class MyInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { if (i

我试图访问应用于castle拦截器内方法的自定义属性,例如:

[MyCustomAttribute(SomeParam = "attributeValue")]
public virtual MyEntity Entity { get; set; }
使用以下代码:

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

当调用该方法时,拦截器触发OK,但该代码不返回自定义属性。如何实现这一点?

尝试使用
Attribute.GetCustomAttribute(…)
静态方法。这很奇怪,但这两种方法有时会因为某些奇怪的原因返回不同的结果。

我想我已经找到了答案-这是因为属性和方法之间的差异。触发拦截器的是get_uu方法,它没有用父属性的属性修饰。

Try

private static Attribute getMyCustomAttribute(IInvocation invocation)
{
   var methodInfo = invocation.MethodInvocationTarget;
   if (methodInfo == null)
   {
      methodInfo = invocation.Method;
   }
   return Attribute.GetCustomAttribute(methodInfo, typeof(MyCustomAttribute), true);
}

你使用的是什么版本的DynamicProxy?谢谢你,伙计,我今天遇到了这个bug,在你的帖子拯救了这一天之前,我都快发疯了。正如您所说,静态方法是有效的,通用的
GetCustomAttribute()
也是有效的。不幸的是,后者仅出现在.NET 4.5中。Just saw声明“此方法忽略属性和事件的inherit参数。若要在继承链中搜索属性和事件的属性,请使用Attribute.GetCustomAttributes方法的适当重载。”非常不一致的设计IMHO.var methodInfo=invocation.MethodInvocationTarget??调用方法;