我可以使用装饰器模式来包装方法体吗?

Mat*_*ves 22 c# design-patterns decorator

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

MyHelper.PerformCall( () => { doStuffWithData(parameters...) });
Run Code Online (Sandbox Code Playgroud)

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

[InteractsWithData]
protected string doStuffWithData(parameters...)
{
     // do stuff...
}
Run Code Online (Sandbox Code Playgroud)

然后基本上,每当doStuffWithData调用时,该方法的主体将作为Actionto 传入MyHelper.PerformCall().我该怎么做呢?

Mat*_*ves 17

所以,我本周末刚刚参加AOP会议,这里有一种方法可以使用PostSharp:

[Serializable]
public class MyAOPThing : MethodInterceptionAspect
{
    public override void OnInvoke(MethodInterceptionArgs args)
    {
        Console.WriteLine("OnInvoke! before");
        args.Proceed();
        Console.WriteLine("OnInvoke! after");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用[MyAOPThing].装饰方法.简单!

  • 问题没有提到价格.此外,还提供免费的Postsharp许可证:https://www.postsharp.net/download (3认同)
  • 这应该是最好的答案.谢谢发帖. (2认同)
  • PostSharp不是免费的 (2认同)

dtb*_*dtb 16

.NET属性是元数据,而不是自动调用的装饰器/活动组件.没有办法实现这种行为.

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

"装饰属性":

[AttributeUsage(AttributeTargets.Method)]
public class MyDecorator : Attribute
{
    public void PerformCall(Action action)
    {
       // invoke action (or not)
    }
}
Run Code Online (Sandbox Code Playgroud)

方法:

[MyDecorator]
void MyMethod()
{
}
Run Code Online (Sandbox Code Playgroud)

用法:

InvokeWithDecorator(() => MyMethod());
Run Code Online (Sandbox Code Playgroud)

辅助方法:

void InvokeWithDecorator(Expression<Func<?>> expression)
{
    // complicated stuff to look up attribute using reflection
}
Run Code Online (Sandbox Code Playgroud)

看看C#中面向方面编程的框架.这些可能提供你想要的.