gpt4 book ai didi

c# - 返回之后或之前触发代码

转载 作者:行者123 更新时间:2023-12-02 13:30:50 25 4
gpt4 key购买 nike

如何在调用 return 之前/之后执行代码的某些部分。例如, return 可能在一个方法中被多次调用,因此我不希望在 return 之前复制粘贴相同的行。

我可能是错的,但有些人告诉我,try block 会使代码运行缓慢,并且我的方法被调用超过 1000 次,因此即使可以使用 try/finally block 完成此任务,我也想避免它。

示例:

void method()
{
MyObject activator = new ...
AnotherObject something = new ...
SomethingElse asdf = new ...
// some other variables
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations
return;
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations
return;
if(..)
// Deactivate activator, close things, confirm user exited
// Do some post calculations
return;
}

现在我需要在每次返回之前或之后执行相同的代码。我的代码需要使用方法顶部定义的变量,这就是我无法外包的原因。这个怎么做?有办法吗?如果出现重复,我深表歉意。

最佳答案

我不太清楚您想要实现的目标,但根据您的帖子,您可以使用可怕的 goto 语句!

public void Test()
{
if (...)
goto Finish;
if (...)
goto Finish;

Finish:
DoSomething();
}
<小时/>

根据您的更新,我肯定会考虑使用 finally block :

void Main()
{
try
{
MyObject activator = new ...
AnotherObject db_connection = new ...
Proxy p = new ...
// some other variables
if(..)
return;
if (...)
return;
}
finally
{
// Deactivate activator, close db connection, call a webservice to confirm user exited
// Do some post calculations
}
}
<小时/>

try-finally的效率

try-finally 模式非常高效。考虑以下代码:

try
{
Console.WriteLine("Foo");
}
finally
{
Console.WriteLine("Bar");
}

这将编译为以下 IL:

IL_0000:  ldstr       "Foo"
IL_0005: call System.Console.WriteLine
IL_000A: leave.s IL_0017
IL_000C: ldstr "Bar"
IL_0011: call System.Console.WriteLine
IL_0016: endfinally

英文的意思是:

Load the string "Foo" and call WriteLine with it. We have a finally statement so when we've called that, go to location IL_0017 - the end of the method. Load string "Bar" and call WriteLine with it. The finally has finished now so we can continue to the location we defined before the finally block.

关于c# - 返回之后或之前触发代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25781886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com