1

这是我扩展 IMethodDecorator 接口的属性类的代码

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Field)]
public class LogAttribute : Attribute, IMethodDecorator
{
    ILogger log = Logger.Factory.GetLogger<Logger>();
    String methodName;


    public LogAttribute() {
    }

    public void Init(object instance, MethodBase method, object[] args)
    {
        methodName = method.Name;
    }

    public void OnEntry()
    {
        Console.WriteLine(methodName);
        log.Debug(methodName);
    }

    public void OnExit()
    {
        Console.WriteLine("Exiting Method");
    }

    public void OnException(Exception exception)
    {
        Console.WriteLine("Exception was thrown");
    }

}

我希望能够将其用作

[log("some logmessage")]
void method() 
{
// some code  
}

有任何想法吗 ?我正在使用方法装饰器 Fody 包。

4

1 回答 1

2

所以我找到了解决我的问题的方法。

基本上我修改了我的课程,比如 -

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Field)]
public class LogAttribute : Attribute, IMethodDecorator
{
    ILogger log = Logger.Factory.GetLogger<Logger>();
    String methodName;

    public String logMessage { get; set; }

    private Lazy<IEnumerable<PropertyInfo>> _properties;
    public MethodBase DecoratedMethod { get; private set; }

    public LogAttribute() {
        this._properties = new Lazy<IEnumerable<PropertyInfo>>(() =>
         this.GetType()
             .GetRuntimeProperties()
             .Where(p => p.CanRead && p.CanWrite));
    }


    public void Init(object instance, MethodBase method, object[] args)
    {
        this.UpdateFromInstance(method);
        methodName = method.Name;
    }

    public void OnEntry()
    {
        log.Debug("Inside" + methodName);
        log.Debug(logMessage);
    }

    public void OnExit()
    {
        Console.WriteLine("Exiting Method");
    }

    public void OnException(Exception exception)
    {
        Console.WriteLine("Exception was thrown");
    }

    private void UpdateFromInstance(MethodBase method)
    {
        this.DecoratedMethod = method;
        var declaredAttribute = method.GetCustomAttribute(this.GetType());

        foreach (var property in this._properties.Value)
            property.SetValue(this, property.GetValue(declaredAttribute));

    }

}

现在我可以使用自定义属性

 [Log(logMessage = "This is Debug Message")]
于 2016-06-01T08:31:59.580 回答