在Afterterthought中使用带参数的Attributes

时间:2014-10-05 12:30:28

标签: c# afterthought

假设我们有这样的属性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false,  Inherited = true)]
public class LogScopeAttribute : Attribute
{ 
    public string Level { get; private set; }

    public LogScopeAttribute(string level)
    {
        Level   = level;
    }
}

在这样的上下文中使用:

public class Cat
{
    [Log.Scope("Important")]
    public void Walk()
    {
    }

    [Log.Scope("Trivial")]
    public void Sit()
    {
    }
}

如何在LevelBefore方法中使用属性After?看起来您只能使用流畅的界面,但由于这一点,我无法引用LogScope属性。

public class LoggingAmender : Amendment<object, object>
{
    public LoggingAmender()
    {
        Methods.Where( m => [...] )
            .Before(LogScope.LogMethodBefore); // how can I refer to 'Level' of LogScope here?
    }
}

1 个答案:

答案 0 :(得分:0)

您可以访问存储该方法的所有属性实例的method.Attribute。

也许你更容易不使用Lambdas。我无法证明代码,我仍然在学习,但这里有我所拥有的:

您的案例中的TDeclaringAttribute是LogScopeAttribute。

   /// <summary>
  /// Pointcut definition for Amendments that are targeted to Methods that have a declaring Attribute defined.
/// </summary>
abstract class MethodAmendment<TType, TDeclaringAttribute> : Amendment<TType, TType>
    where TDeclaringAttribute : Attribute
{
    public MethodAmendment()
    {
        foreach (Method method in Methods)
        {
            //todo ?? look for base class versions of method ? should be covered by afterthought itself ?
            TDeclaringAttribute attribute = method.Attributes.OfType<TDeclaringAttribute>().FirstOrDefault();
            if (attribute != null)
            {
                ApplyMethodChanges(method, attribute);
            }
        }
    }

    protected abstract void ApplyMethodChanges(Method method, TDeclaringAttribute attribute);
}