例如:我有一个类似于以下内容的自定义属性类:
[System.AttributeUsage(System.AttributeTargets.Method)
]
public class Yeah: System.Attribute
{
public double whatever = 0.0;
}
现在我用它来装饰一些方法:
[Yeah(whatever = 2.0)]
void SampleMethod
{
// implementation
}
是否可以通过方面注入代码来访问Yeah属性?我更喜欢AOP的postharp框架,但我也对任何其他解决方案感到满意,因为我认为postharp中有这样的功能,但仅在专业版中提供(在此处提及:PostSharp Blog)
答案 0 :(得分:2)
看看NConcern .NET AOP Framework。这是一个我积极工作的新开源项目。
//define aspect to log method call
public class Logging : IAspect
{
//define method name console log with additional whatever information if defined.
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//get year attribute
var year = method.GetCustomAttributes(typeof(YearAttribute)).Cast<YearAttribute>().FirstOrDefault();
if (year == null)
{
yield return Advice.Basic.After(() => Console.WriteLine(methode.Name));
}
else //Year attribute is defined, we can add whatever information to log.
{
var whatever = year.whatever;
yield return Advice.Basic.After(() => Console.WriteLine("{0}/whatever={1}", method.Name, whatever));
}
}
}
public class A
{
[Year(whatever = 2.0)]
public void SampleMethod()
{
}
}
//Attach logging to A class.
Aspect.Weave<Logging>(method => method.ReflectedType == typeof(A));
//Call sample method
new A().SampleMethod();
//console : SampleMethod/whatever=2.0
我的日志记录方面只是在调用方法时编写方法名称。它包括定义时的任何信息。