通过调用另一个方法退出方法

时间:2016-08-24 14:45:21

标签: c#

所以我想通过调用另一个方法来退出方法或函数的执行。到目前为止,我只发现了 else 的问题而且没有我想要的任何问题。

示例如下..

public static void SomeMethod() {
    // some code
    ExitMethod();
    // the next line of code will never be executed
    Console.WriteLine("Test");
}

private static void ExitMethod() {
    // if possible the execution of the Method above will be stopped here
}

ExitMethod 将像 return 一样工作,只是因为它是一种方法我可以更轻松地添加 if 或其他条件它。如果我经常在我的程序集中使用 ExitMethod ,我可以轻松地重构停止执行调用方法的条件。

例如,这可以用于明显不安全的保护dll的尝试,因此它需要一个串行密钥,并且只有在给出正确的密钥时,它才会启用一些静态bool,然后每次调用函数时都会检查它dll。

提前致谢:)

编辑: 通过使用可以为取消任务调用的另一种方法,我想避免类似的事情:

public static void SomeMethod() {
    if (ExitMethod) return;
}

目标是只需要调用 ExitMethod 方法来处理事情。

1 个答案:

答案 0 :(得分:4)

来自问题中的评论:

  

为什么没有更好的解决方案[...]?

隐式流量控制通常被视为反模式 - 甚至存在反对存在例外的论据。存在故意不包含任何形式的隐式流量控制的语言(例如Go)。

您可以使用以下几种方法。

显式流量控制

public bool ExitMethod() => // ...

public void SomeMethod()
{
  if (ExitMethod()) return;
  Console.WriteLine("Test");
}

如果没有DocComments,布尔返回值可能会令人困惑。枚举将导致自我记录代码:

public enum ExitParentStatus : byte
{
  Continue, Return
}

public ExitParentStatus ExitMethod() => // ...

public void SomeMethod()
{
  if (ExitMethod() == ExitParentStatus.Return) return;
  Console.WriteLine("Test");
}

带状态

的显式流控制
public enum RequestStatus : byte
{
  Processing, Handled
}

public class Request
{
  public RequestStatus Status { get; set; }
}

public void ExitMethod(Request request) => // ...

public void SomeMethod(Request request)
{
  ExitMethod();
  if (request.Status == Handled) return;
  Console.WriteLine("Test");
}

使用收益率回报

这为其他开发人员提供了线索,他们正在接近设计不佳的代码,从而略微降低了出错的可能性。

public void ExecuteConditionalCoroutine(IEnumerable<bool> coroutine)
{
  foreach (var result in coroutine)
  {
    if (result) return;
  }
}

public bool ExitMethod() => // ...

public IEnumerable<bool> SomeMethod()
{
  yield return ExitMethod();
  Console.WriteLine("Test");
}

ExecuteConditionalCoroutine(SomeMethod());

例外

如果您想使代码无法调试,请使用此选项。

public bool ExitMethod() { throw new ExitParentMethodException(); }

public void SomeMethod()
{
  try
  {
    ExitMethod();
    Console.WriteLine("Test");
  }
  catch (ExitParentMethodException) { }
}

后编译

使用post-sharp之类的内容自动注入分支。对于完全无法维护的代码,这是一种很好的方法。

[ExitsParentMethod]
public bool ExitMethod() => // ...

public void SomeMethod()
{
  ExitMethod();
  Console.WriteLine("Test");
}
相关问题