C#out参数VS回报 [英] C# out parameters vs returns
问题描述
所以,我是新来的C#和我有困难理解退出
。而不是仅仅从函数返回的东西。
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);
}
}
比较这个
compare to this
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();
}
}
第一个是我会怎么一般做到这一点。是否有一个原因,我可能要使用退出
,而不是仅仅一个return语句?据我所知, REF
允许双向沟通,而我一般不应该使用 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.
不过有出和返回语句之间的差异,就像上面显示?从句法上讲是有什么原因赞成一方或另一方?
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?
推荐答案
一个良好的使用出
而不是收益
的结果是尝试,你可以在某些API见
模式例如 Int32.TryParse(...)
。在这个模式中,返回值是用来表明操作(而不是异常)的成功或失败,而退出
参数用于返回实际结果。
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,尝试捕获:一些基准已在此的其他问题被提出)
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#out参数VS回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!