我可以使用装饰器模式来包装方法体吗? [英] Can I use the decorator pattern to wrap a method body?

查看:20
本文介绍了我可以使用装饰器模式来包装方法体吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆具有不同签名的方法.这些方法与脆弱的数据连接交互,所以我们经常使用辅助类来执行重试/重新连接等.像这样:

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...) });

这工作正常,但它会使代码有点混乱.我更愿意做的是装饰与数据连接交互的方法,如下所示:

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 被调用时,该方法的主体将作为 Action 传递给 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 no way to achieve this behaviour.

您可以使用属性来实现装饰器,方法是将装饰器代码放在 Attribute 类中,并使用辅助方法调用该方法,该方法使用反射调用 Attribute 类中的方法.但我不确定这会比直接调用装饰器方法"有很大的改进.

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.

这篇关于我可以使用装饰器模式来包装方法体吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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