C#输出参数与返回

C# out parameters vs returns(C#输出参数与返回)

本文介绍了C#输出参数与返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是 C# 新手,我很难理解 out.而不是仅仅从函数中返回一些东西

So I am new to C# and I am having difficulty understanding out. As opposed to just returning something from a function

using System;
class ReturnTest
{
    static double CalculateArea()
    {
         double r=5;
         double area = r * r * Math.PI;
         return area;
    }

    static void Main()
    {
         double output = CalculateArea();
         Console.WriteLine("The area is {0:0.00}", output);
    } 
 }

对比一下

 using System;
 class ReturnTest
 {
     static void CalculateArea(out double r)
     {
         r=5;
         r= r * r * Math.PI;
     }

     static void Main()
     {
         double radius;
         CalculateArea(out radius);
         Console.WriteLine("The area is {0:0.00}",radius );
         Console.ReadLine();
     }
}

第一个是我通常会怎么做.我是否有理由要使用 out 而不仅仅是 return 语句?我了解 ref 允许 2 路通信,并且我通常不应该使用 ref 除非该函数正在对我发送的变量执行某些操作.

The first one is how I would generally do it. Is there a reason why I may want to use out instead of just a return statement? I understand that ref allows for 2 way communication, and that I generally shouldn't use ref unless the function is doing something with the variable I am sending it.

但是,out 和 return 语句之间有区别吗,如上所示?在语法方面是否有理由偏爱其中一个?

However is there a difference between out and return statements, like shown above? Syntax-wise is there a reason to favor one or the other?

推荐答案

out而不是return的一个很好的用法是Try 模式,例如 Int32.TryParse(...).在此模式中,返回值用于表示操作成功或失败(与异常相反),out 参数用于返回实际结果.

A good use of out instead of return for the result is the Try pattern that you can see in certain APIs, for example Int32.TryParse(...). In this pattern, the return value is used to signal success or failure of the operation (as opposed to an exception), and the out parameter is used to return the actual result.

Int32.Parse 的优点之一是速度,因为可以避免异常.在这个其他问题中提出了一些基准:解析性能(如果,TryParse,Try-Catch)

One of the advantages with respect to Int32.Parse is speed, since exceptions are avoided. Some benchmarks have been presented in this other question: Parsing Performance (If, TryParse, Try-Catch)

这篇关于C#输出参数与返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C#输出参数与返回

基础教程推荐