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#输出参数与返回
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
