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#输出参数与返回
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30