[英]Is it possible to execute a specific block of code before the OnPost() method is executed in the .cshtml.cs file on a set pages?
[英]Execute Method Before and After Code Block
如何在括號中包含一些代碼來執行以下操作?
MyCustomStatement(args){
// code goes here
}
因此,在括號中的代碼執行之前,它將調用一個方法,當括號中的代碼完成執行時,它將調用另一個方法。 有這樣的事嗎? 我知道當我可以簡單地在代碼之前和之后調用方法時,這樣做似乎是多余的,但我只是很好奇。 我不知道怎么說這個,因為我是編程的新手。
謝謝!
您可以通過將代碼存儲在一個抽象類中來執行此操作,該類在您調用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);
}
要真正實現您想要的,您可以使用委托:
Action<Action> callWithWrap = f => {
Console.WriteLine("Before stuff");
f();
Console.WriteLine("After stuff");
};
callWithWrap(() => {
Console.WriteLine("This is stuff");
});
這需要在塊中添加“奇怪的語法”,並了解C#中的委托和匿名函數的工作方式。 更常見的是,如果你在課堂上這樣做,請使用@ CodeCaster答案中演示的技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.