【问题标题】:Parameter attribute not showing up参数属性不显示
【发布时间】:2012-04-18 16:19:05
【问题描述】:

我正在编写一个审计部分,并尝试使用属性将参数标记为应记录在审计中以获取更多信息的方法。但是,无论出于何种原因,我似乎无法检查该属性是否存在。

我的代码:

  [Audit(AuditType.GetReport)]
  public Stream GetReportStream([AuditParameter] Report report)
  {
     ...
  }

  [AttributeUsage(AttributeTargets.Parameter)]
  public class AuditParameterAttribute : Attribute
  {
  }

而且,在我试图获取它的拦截器内部:

foreach (ParameterInfo param in invocation.Method.GetParameters ())
{
   var atts = CustomAttributeData.GetCustomAttributes (param);
   if (param.IsDefined (typeof(AuditParameterAttribute), false))
   {
      attributes.Add (param.Name, invocation.Arguments[param.Position].ToString ());
   }
}

我开始添加一些额外的调用来尝试让某些东西起作用;这就是为什么额外的var atts 在那里。 invocation 变量包含有关所调用方法的信息,我能够从中获取表示参数的 ParameterInfo 对象。但是,无论我尝试过什么,我都无法从中获得任何自定义属性。

我在这里做错了什么?

【问题讨论】:

    标签: c# custom-attributes


    【解决方案1】:

    知道了。原来这是我使用 Castle 缺乏经验的问题。我意识到它正在通过基于被调用类接口的代理,该类没有我正在寻找的属性。因此,将我的代码更改为:

    foreach (ParameterInfo param in invocation.MethodInvocationTarget.GetParameters ())
    {
       if (param.IsDefined (typeof(AuditParameterAttribute), false))
       {
          attributes.Add (param.Name, invocation.Arguments[param.Position].ToString ());
       }
    }
    

    使用 MethodInvocationTarget 而不是 Method 解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2017-09-13
      • 2014-01-20
      • 2019-04-12
      • 1970-01-01
      相关资源
      最近更新 更多