假设我们有这样的属性:
[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
和Before
方法中使用属性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?
}
}
答案 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);
}