我可以使用Decorator模式来包装方法体? [英] Can I use the decorator pattern to wrap a method body?
问题描述
我有一堆具有不同签名的方法。这些方法有脆弱的数据连接交互,所以我们经常使用一个辅助类来执行重试/重新连接,等等,像这样:
I have a bunch of methods with varying signatures. These methods interact with a fragile data connection, so we often use a helper class to perform retries/reconnects, etc. Like so:
MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
这工作得很好,但它可以使代码有点cluttery。我宁愿做的是装饰与像这样的数据连接的交互方式:
And this works fine, but it can make the code a little cluttery. What I would prefer to do is decorate the methods that interact with the data connection like so:
[InteractsWithData]
protected string doStuffWithData(parameters...)
{
// do stuff...
}
和则基本上,只要 doStuffWithData
被调用,该方法的机构将被作为一个动作<传递/ code>到
MyHelper.PerformCall()
。我该怎么做呢?
And then essentially, whenever doStuffWithData
is called, the body of that method would be passed in as an Action
to MyHelper.PerformCall()
. How do I do this?
推荐答案
.NET属性是元数据,而不是装饰/自动被调用的活性成分。没有办法实现这种行为。
.NET Attributes are meta-data, not decorators / active components that automatically get invoked. There is not way to achieve this behaviour.
您可以使用属性,通过将装饰码的属性类实现的装饰,并呼吁有一个辅助方法调用方法使用反射在属性类中的方法。但我不知道这将是在只调用直接在装饰法的一大进步。
You could use attributes to implement decorators by putting the decorator code in the Attribute class and call the method with a helper method that invokes the method in the Attribute class using Reflection. But I'm not sure this would be a big improvement over just calling the "decorator-method" directly.
的装饰属性:
[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
public void PerformCall(Action action)
{
// invoke action (or not)
}
}
的方法:的
[MyDecorator]
void MyMethod()
{
}
的用法:的
InvokeWithDecorator(() => MyMethod());
的辅助方法:的
void InvokeWithDecorator(Expression<Func<?>> expression)
{
// complicated stuff to look up attribute using reflection
}
看一看的面向方面的编程框架在C#。这些可以提供你想要的东西。
Have a look at frameworks for Aspect Oriented Programming in C#. These may offer what you want.
这篇关于我可以使用Decorator模式来包装方法体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!