C# out parameters vs returns(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您可以在某些 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
的优点之一是速度,因为可以避免异常.在这个其他问题中提出了一些基准:解析性能(如果,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#输出参数与返回
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01