0

假设我们有这样的属性:

[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()
    {
    }
}

如何Level在我的BeforeAfter方法中使用该属性?似乎您只能使用流利的界面,但因此我无法引用该LogScope属性。

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

1 回答 1

0

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

也许你不使用 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);
}
于 2015-03-03T18:06:20.653 回答