c# - 通过调用另一个方法退出一个方法

标签 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 将像返回语句一样工作,只是因为它是一种方法,我可以更轻松地向它添加 if 或其他条件。如果我经常在我的程序集中使用 ExitMethod,我可以轻松地重构调用 Method 的执行将停止的条件。

例如,这可以用于保护 dll 的明显不安全的尝试,因此它需要一个序列 key ,并且只有在提供正确的序列 key 时,它才会启用一些静态 bool,然后每次从 dll 调用函数时都会检查该静态 bool 值。

提前致谢 :)

编辑:
通过使用可以为取消任务调用的另一种方法,我想避免类似的事情:
public static void SomeMethod() {
    if (ExitMethod) return;
}

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

最佳答案

从问题中的评论:

why isn't there a better solution [...]?



隐式流控制通常被认为是一种反模式——甚至有反对存在异常的论据。存在故意不包含任何形式的隐式流控制的语言(例如 Go)。

以下是您可以使用的一些方法。

显式流控制
public bool ExitMethod() => // ...

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

如果没有 DocComments, bool 返回值可能会令人困惑。枚举将导致自记录代码:
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");
}

使用 yield 返回

这为其他开发人员提供了他们正在处理设计不佳的代码的线索,从而略微减少了出现错误的机会。
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());

异常(exception)

如果您想让您的代码无法调试,请使用此选项。
public bool ExitMethod() { throw new ExitParentMethodException(); }

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

编译后

使用类似 post-sharp自动注入(inject)分支。对于完全不可维护的代码,这是一种很好的方法。
[ExitsParentMethod]
public bool ExitMethod() => // ...

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

关于c# - 通过调用另一个方法退出一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39126502/

相关文章:

c# - 如何让用户登录系统并仅在用户单击注销按钮后注销?

c# - 单核cpu上的C#并行和多线程

c# - .Net 中 Random 的并发问题?

c# - .NET Core HttpClient 上传字节数组给出不受支持的媒体类型错误

c# - 具有始终相等编号的 GUID

c# - 为什么 BinaryWriter 会在流的开头添加乱码?你如何避免它?

c# - 监视文件的更改

c# - 如何为 `dotnet new` 设置变量?

c# - 使用C#从csv文件将大量行插入mysql

c# - 隐式转换数组