Execute方法之前和代码块之后 [英] Execute Method Before and After Code Block
问题描述
我怎么能换一些代码在括号中做到以下几点?
How could I wrap some code in brackets to do the following?
MyCustomStatement(args){
// code goes here
}
因此,在括号中的代码执行前, LL调用方法时括号中的代码执行完毕,将调用另一个方法。是否有这样的事情吗?我知道这似乎是多余的做到这一点时,我根本就前后代码和所有后调用的方法,但我只是很好奇。我不知道该怎么这个词正是因为我是新来编程。
So that before the code in the brackets executes, it'll call a method and when the code in the brackets finishes executing it will call another method. Is there such a thing? I know it seems redundant to do this when I can simply call the methods before and after the code and all, but I simply was curious. I don't know how to word this exactly because I'm new to programming.
谢谢!
推荐答案
您可以通过存储在执行一个抽象类的代码之前和之后为你的代码,当你调用运行()$做到这一点C $ C>:
You can do this by storing the code in an abstract class that executes the "before" and "after" code for you when you call 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();
当然,那么每一件定制的代码,就必须创建一个新的类,它可能小于希望的。
Of course then for every piece of custom code you'll have to create a new class, which may be less than desirable.
这是更简单的方法是使用一个动作
:
An easier way would be to use an 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);
}
这篇关于Execute方法之前和代码块之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!