可能重复:
通过属性的C#wrap方法
我想实现这样的功能:
[Atomic]
public void Foo()
{
/* foo logic */
}
Run Code Online (Sandbox Code Playgroud)
其中[Atomic]attribute是一个属性,它在事务范围内包装函数逻辑:
using(var scope = new TransactionScope())
{
/* foo logic */
scope.Complete();
}
Run Code Online (Sandbox Code Playgroud)
怎么写这样的属性?
我之前问过基本相同的问题,我知道这可以用AOP完成,但我没有提到我正在寻找一些最简单的概念证明实现或有用的文章,可以帮助我用纯.NET编写这个框架(我想使用RealProxy和MarshalByRefObject类型,我已阅读浏览相关问题).
我需要完全解决这个显示的例子.这似乎是一个基本的东西,所以我想从头开始学习如何做到这一点.它现在不需要安全和灵活.
我是面向方面编程思想的新手,但我想探索在我的项目中使用它来处理日志记录,报告等的想法.为此,我有一些问题:
我正在将类A(我从其他人导入,因此我无法修改它)实例化到我的类X.
有没有办法可以拦截或包装对A中方法的调用?即,在下面的代码中我可以打电话
x.a.p1()
Run Code Online (Sandbox Code Playgroud)
并获得输出
X.pre
A.p1
X.post
Run Code Online (Sandbox Code Playgroud)
很多TIA!
class A:
# in my real application, this is an imported class
# that I cannot modify
def p1(self): print 'A.p1'
class X:
def __init__(self):
self.a=A()
def pre(self): print 'X.pre'
def post(self): print 'X.post'
x=X()
x.a.p1()
Run Code Online (Sandbox Code Playgroud)