C# 输出参数 vs 返回值 [英] C# out parameters vs returns
问题描述
所以我是 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您可以在某些 API 中看到的 code> 模式,例如
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
的优点之一是速度,因为避免了异常.在另一个问题中已经提出了一些基准测试:解析性能(If、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# 输出参数 vs 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!