如何在 C# 中显示方法返回成功或失败而不返回值?

发布于 2024-10-28 23:06:23 字数 195 浏览 4 评论 0原文

我知道在其他语言(如 C/C++)中,您会返回一个类似 SUCCESS 的值,该值将向调用方法指示该方法返回成功或失败。

在 C# 中是否有一种“好”方法可以做到这一点,而不需要 SUCCESS 返回变量?我想到了抛出异常,但我不确定如何实现这一点。您是否可以使用自己的错误消息抛出自定义异常?

示例代码将不胜感激。

先感谢您。

I know in other languages like C/C++ you would return a value like SUCCESS which would indicate to the calling method that the method returned successfully, or failed.

Is there a "nice" way to do this in C# without needing a SUCCESS return variable? Throwing an exception comes to mind, but I am not sure how one would implement this. Is there a custom exception you could throw with your own error message?

Sample code would be greatly appreciated.

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

泪是无色的血 2024-11-04 23:06:23

1)我不建议使用异常,除非失败是“异常的”。例如,它失败了,这意味着需要处理一些事情。它们比“false”类型返回慢。

2)为什么要试图避免返回值?一定不能有返回值吗?

1) I wouldn't recommend using an exception unless the failure was "exceptional." For instance, it failed and that means something that needs to be handled. They are slower than a "false" type return.

2) Why are you trying to avoid a return value? Must you have no return values?

兔小萌 2024-11-04 23:06:23

不要使用异常进行流量控制或“成功”指示。

如果除了返回参数之外还希望有成功或失败的指示符,则可以在方法签名中使用 out bool 参数。

public SomeObject DoingSomethingHere(out bool success)
{


}
if (!success)
{
    // some compensating action
}

Do not use exceptions for flow control or an indication of a 'success'.

If you want to have an indicator for success or failure in addition to a return parameter, you can use an out bool parameter in your method signature.

public SomeObject DoingSomethingHere(out bool success)
{


}
if (!success)
{
    // some compensating action
}
铁轨上的流浪者 2024-11-04 23:06:23

您指的是 bool 数据类型吗?

函数定义示例:

public static bool DoSomething()
{
    if ( some || condition )
        return true;
    else
        return false;
}

使用示例:

public static void main()
{
    if ( DoSomething() )
        Console.WriteLine( "SUCCESS" );
    else
        Console.WriteLine( "FAILURE" );
}

Are you refering to the bool data type?

Example of function definition:

public static bool DoSomething()
{
    if ( some || condition )
        return true;
    else
        return false;
}

Example of usage:

public static void main()
{
    if ( DoSomething() )
        Console.WriteLine( "SUCCESS" );
    else
        Console.WriteLine( "FAILURE" );
}
兔姬 2024-11-04 23:06:23

如果您的方法是void,那么它返回而不抛出异常的事实被认为是成功的。

如果您的方法不是 void,则特定返回值可能会被解释为执行不成功,例如:

  • bool 方法返回 false
  • 任何返回 引用类型返回的方法>空

If your method is void, then the fact that it returned without throwing an exception is considered SUCCESS.

If your method is something other than void, then particular return values might be interpreted as unsuccessful executions, for example:

  • bool method returning false
  • any reference type-returning method returning null
爱,才寂寞 2024-11-04 23:06:23

您可以从 Exception 派生您自己的异常。

您可以返回布尔值或某些数字约定。

在 C# 中,如果您想返回成功/失败,则可以使用比指针更容易使用的输出参数以及产品输出。

对于特殊的事情,我倾向于例外。逻辑事物的逻辑回报。即不要使用异常来控制程序操作。如果文件操作意外失败,则抛出异常。如果应用程序需要查找文件并且通常希望有时找不到它作为正常操作,那么我不希望调用者捕获异常,而是简单地返回 bool 并通过应用程序选择适当的逻辑路径。

You can derive your own exceptions from Exception.

You can return a bool or some numeric convention.

In C#, you have output parameters which are a little easier to use than pointers if you want to return success/fail, but also product output.

I tend to go with exceptions for exceptional things. Logical returns for logical things. i.e. Don't use exceptions to control program operations. If a file operation unexpectedly fails, then throw an exception. If the app needs to look for a file and generally expects to not find it sometimes as a normal operation, I would not expect the caller to catch an exception, but instead to simply return a bool and choose an appropriate logical path through the applciation.

北城半夏 2024-11-04 23:06:23

听起来您想指示方法在不使用返回值或异常的情况下未成功完成。 out bool 参数怎么样?

public void Execute(out bool success) {
      try {
          //...
          success = true;
      } catch {
          success = false
      }
}

建议这样做,但既然你问了......

It sounds like you want to indicate that a method did not complete successfully without using a return value, or an exception. What about an out bool parameter?

public void Execute(out bool success) {
      try {
          //...
          success = true;
      } catch {
          success = false
      }
}

I would not recommend doing this, but since you asked....

两个我 2024-11-04 23:06:23

对于某些类型的故障,自定义异常无疑是一个好方法。一种简单的方法是在公共库中创建一个 DomainException 类(或者您想要为应用程序的问题域调用的任何名称等),该类继承自 Exception 并添加您认为对自定义域例外有用的任何特定信息。 (也许是特定的代码,也许是有关当前环境的信息,这些信息在标准 Exception 中可能不可用,等等)

从那里,您可以创建继承自该异常的更具体的异常,例如 DataIntegrityException 例如,如果一个方法接收到在技术层面上有意义但违反自定义业务验证规则等的输入,则可能会抛出该异常。

For certain types of failures, a custom exception is certainly a good way to go. One simple approach would be to create a DomainException class (or whatever you want to call it for your application's problem domain, etc.), in a common library, which inherits from Exception and adds any particular information you think would be useful for a custom domain exception. (Maybe specific codes, maybe information about the current environment which may not be available in the standard Exception, etc.)

From there, you can create more specific exceptions which inherit from that, such as DataIntegrityException which can be thrown if, for example, a method receives input which makes sense on a technical level but violates custom business validation rules, etc.

初见 2024-11-04 23:06:23

我想到的方法是不抛出异常...

基本上有四种方法可以从函数中获取消息:

  • 返回某些内容
  • 使用 out 变量
  • 抛出异常 将
  • var 设置为类的另一个成员

I如果出现意外错误,则会抛出异常。如果我预计某些东西不会一直有效,我会使用返回值。

Not throwing an exception would be the way that comes to my mind...

There are basically four ways you can get a message out of a function:

  • return something
  • use an out variable
  • throw an exception
  • set a var to another member of the class

I would throw an exception if something unexpectedly goes wrong. If I expect something not to work all the time, I would use a return value.

淡莣 2024-11-04 23:06:23

您可以返回状态变量,例如枚举、整数或布尔值。问题在于调用者必须知道不同的返回值意味着什么。有时 true 意味着成功,有时意味着有错误。此外,如果调用失败,直接调用者可能不知道该怎么办,需要在每个方法因调用失败而失败时“冒泡”失败。

Try-throw-catch 是处理您知道可能会失败的事情的首选模式,并在失败时控制执行流程:

public void MightFail()
{
   //obviously your code will do something a little more meaningful
   if(new Random().Next(2) == 0) throw new Exception("I failed");
   return;
}

public void RunRiskyMethod()
{
   var failures = 0;
   var successes = 0;
   var totalRuns = 0;

   for(var i=1;i<10000;i++)
   {
       try
       {
          MightFail();
          //if the previous line throws an exception, the below lines will not execute
          successes++;
          Console.WriteLine("Success!");
       }
       catch(Exception) //I didn't name the exception because we don't need its info.
       {
          //These lines ONLY execute if an exception was thrown from within the try block
          failures++;
          Console.WriteLine("Failure!");
       }
       finally
       {
          //this code ALWAYS executes, even if an exception is thrown and not caught
          totalRuns++;
       }
   }

   Console.WriteLine(String.Format("{0} Successes, {1} Failures.", successes, failures);
}

You can return a status variable, such as an enumeration, integer or boolean. The trouble is that the caller has to know what different return values mean. Sometimes true means it was successful, sometimes it means there was an error. Also, the immediate caller may not know what to do if the call fails, requiring failures to "bubble up" as each method fails because its call did.

Try-throw-catch is the go-to pattern for handling things you know might fail, and controlling execution flow if/when it does:

public void MightFail()
{
   //obviously your code will do something a little more meaningful
   if(new Random().Next(2) == 0) throw new Exception("I failed");
   return;
}

public void RunRiskyMethod()
{
   var failures = 0;
   var successes = 0;
   var totalRuns = 0;

   for(var i=1;i<10000;i++)
   {
       try
       {
          MightFail();
          //if the previous line throws an exception, the below lines will not execute
          successes++;
          Console.WriteLine("Success!");
       }
       catch(Exception) //I didn't name the exception because we don't need its info.
       {
          //These lines ONLY execute if an exception was thrown from within the try block
          failures++;
          Console.WriteLine("Failure!");
       }
       finally
       {
          //this code ALWAYS executes, even if an exception is thrown and not caught
          totalRuns++;
       }
   }

   Console.WriteLine(String.Format("{0} Successes, {1} Failures.", successes, failures);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文