C# 我可以用面向方面的方法访问自定义方法属性吗?
例如:我有一个类似于以下内容的自定义属性类:C# 我可以用面向方面的方法访问自定义方法属性吗?,c#,.net,aop,postsharp,C#,.net,Aop,Postsharp,例如:我有一个类似于以下内容的自定义属性类: [System.AttributeUsage(System.AttributeTargets.Method) ] public class Yeah: System.Attribute { public double whatever = 0.0; } 现在我用它装饰一些方法如下: [Yeah(whatever = 2.0)] void SampleMethod { // implementation } 是否可以通过方面注入代码
[System.AttributeUsage(System.AttributeTargets.Method)
]
public class Yeah: System.Attribute
{
public double whatever = 0.0;
}
现在我用它装饰一些方法如下:
[Yeah(whatever = 2.0)]
void SampleMethod
{
// implementation
}
是否可以通过方面注入代码来访问Yeah属性?我更喜欢用于AOP的postsharp框架,但我也对其他任何解决方案感到满意,因为我认为postsharp中有这样一个功能,但只在专业版中提供(这里提到:)看看。这是我积极参与的一个新的开源项目
//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
//定义要记录方法调用的方面
公共类日志记录:IAspect
{
//定义方法名控制台日志,如果已定义,则包含其他任何信息。
公共IEnumerable建议(MethodInfo方法)
{
//获取年份属性
var year=method.GetCustomAttributes(typeof(YearAttribute)).Cast().FirstOrDefault();
如果(年份==null)
{
返回Advice.Basic.After(()=>Console.WriteLine(methode.Name));
}
否则//Year属性被定义,我们可以将任何信息添加到日志中。
{
var whatever=年份,whatever;
返回Advice.Basic.After(()=>Console.WriteLine(“{0}/whatever={1}”,method.Name,whatever));
}
}
}
公共A类
{
[年份(无论什么=2.0)]
公共无效采样方法()
{
}
}
//将日志记录附加到类。
Aspect.Weave(method=>method.ReflectedType==typeof(A));
//调用示例方法
新的A().SampleMethod();
//控制台:SampleMethod/whatever=2.0
我的日志方面只是在调用方法时写入方法名称。它包括定义时的所有信息。您希望如何处理该值?例如,在一些私有方法中使用它,等等……我想用它来编写一种特殊的日志文件。一些方法应该在成功返回后将属性写入此日志文件。F.e.我有一些状态机,希望记录退出事务,但不想将此日志添加到代码中的每个方法中,但使用属性和方面。是否可以将版本作为方面属性本身的参数?对不起。它不是版本,而是公共成员字段“whatever”