类装饰器声明静态成员(例如,对于log4net)? [英] Class decorator to declare static member (e.g., for log4net)?

查看:88
本文介绍了类装饰器声明静态成员(例如,对于log4net)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是log4net,我们的代码中包含很多内容:

I'm using log4net, and we have a lot of this in our code:

public class Foo {
    private static readonly ILog log = LogManager.GetLogger(typeof(Foo));
    ....
}

一个缺点是,这意味着我们重新粘贴整个10个单词的部分,然后时不时有人忘记更改类名。 log4net常见问题解答也提到了这种替代可能性,甚至更冗长:

One downside is that it means we're pasting this 10-word section all over, and every now and then somebody forgets to change the class name. The log4net FAQ also mentions this alternative possibility, which is even more verbose:

public class Foo {
    private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    ...
}

是否可以编写装饰器来定义这个?我真的很想简单地说:

Is it possible to write a decorator to define this? I'd really like to say simply:

[LogMe]  // or perhaps: [LogMe("log")]
public class Foo {
    ...
}

I'我在其他语言中也做过类似的事情,但是从来没有像C#这样的静态编译语言。我可以从装饰者定义班级成员吗?

I've done similar things in other languages, but never a statically-compiled language like C#. Can I define class members from a decorator?

编辑:嘿。我是Lisp程序员我很欣赏切换语言的建议,但实际上,如果我打算切换语言以获得更好的元编程功能,那么我会一直使用Lisp,而不是半途而废。不幸的是,在该项目中不能使用其他语言。

Edit: Heh. I'm a Lisp programmer. I appreciate the suggestions to switch languages, but really, if I was going to switch languages for better metaprogramming capabilities, I'd go all the way to Lisp instead of being half-assed about it. Unfortunately using a different language isn't an option on this project.

推荐答案

这正是AOP的任务-面向方面的编程。看看 PostSharp ,它是一个.NET AOP框架,它将使您能够准确地完成自己的工作

This is exactly a task for AOP - Aspect Oriented Programming. Have a look at PostSharp, it's a .NET AOP framework, it will allow you to do exactly what you want.

这可以通过在编译后修改(或编织)IL代码,并将日志记录方面添加到修饰的方法中来实现。

This works by modifying (or weaving) IL code in post-compilation, and adding the logging aspect to the decorated method.

编辑::看来,PostSharp现在是一种商业产品。如果您正在寻找开源(免费)解决方案,我建议 LinFu AOP

It appears that PostSharp now is a commercial product. If you're looking for an open-source (free) solution, I suggest LinFu AOP.

这篇关于类装饰器声明静态成员(例如,对于log4net)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆