代码块之前和之后的执行方法

时间:2014-10-21 10:13:06

标签: c# .net

如何在括号中包含一些代码以执行以下操作?

MyCustomStatement(args){
// code goes here
}

因此,在括号中的代码执行之前,它将调用一个方法,当括号中的代码完成执行时,它将调用另一个方法。有这样的事吗?我知道当我可以简单地在代码之前和之后调用方法时,这样做似乎是多余的,但我只是很好奇。我不知道怎么说这个,因为我是编程的新手。

谢谢!

2 个答案:

答案 0 :(得分:6)

您可以通过将代码存储在执行"之前"的抽象类中来实现此目的。 """"致电Run()时的代码:

public abstract class Job
{
    protected virtual void Before()
    {
        // Executed before Run()
    }

    // Implement to execute code
    protected abstract void OnRun();

    public void Run()
    {
        Before();
        OnRun();
        After();
    }

    protected virtual void After()
    {
        // Executed after Run()
    }
}

public class CustomJob : Job
{
    protected override void OnRun()
    {
        // Your code
    }
}

在调用代码中:

new CustomJob().Run();

当然,对于每一段自定义代码,您都必须创建一个新类,这可能不太理想。

更简单的方法是使用Action

public class BeforeAndAfterRunner
{
    protected virtual void Before()
    {
        // Executed before Run()
    }

    public void Run(Action actionToRun)
    {
        Before();
        actionToRun();
        After();
    }

    protected virtual void After()
    {
        // Executed after Run()
    }
}

你可以这样打电话:

public void OneOfYourMethods()
{
    // your code
}

public void RunYourMethod()
{
    new BeforeAndAfterRunner().Run(OneOfYourMethods);
}

答案 1 :(得分:3)

要真正实现您想要的目标,您可以使用委托:

Action<Action> callWithWrap = f => {
    Console.WriteLine("Before stuff");
    f();
    Console.WriteLine("After stuff");
};

callWithWrap(() => {
    Console.WriteLine("This is stuff");
});

这需要添加&#34;奇怪的语法&#34;到您的块,并了解C#中的委托和匿名函数如何工作。更常见的是,如果你在课堂上这样做,请使用@CodeCaster答案中演示的技巧。

相关问题