【问题标题】:Can I access custom method attributes with an aspect-oriented approach?我可以使用面向方面的方法访问自定义方法属性吗?
【发布时间】:2016-12-12 19:44:12
【问题描述】:

例如:我有一个类似下面的自定义属性类:

[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 中有这样一个功能,但仅在专业版中可用(此处提到:PostSharp Blog

【问题讨论】:

  • 你想用这个值做什么?例如。在一些私有方法等中使用它...
  • 我想用它来写一种特殊的日志文件。某些方法应该在成功返回后将属性写入此日志文件。 F.e.我有一些状态机,想要记录退出事务,但不想将此日志记录添加到代码中的每个方法中,但带有属性和方面。
  • 是否可以将版本作为方面属性本身的参数?
  • 对不起。它不是版本,而是公共成员字段“随便”

标签: c# .net aop postsharp


【解决方案1】:

看看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

我的日志记录方面只是在方法调用时写入方法名称。它包括定义时的任何信息。

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2014-06-26
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多