为什么使用输出参数而不是返回值 [英] Why output parameters are used rather than return value

查看:91
本文介绍了为什么使用输出参数而不是返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用输出参数而不是返回值。



输出参数有什么优点。b / w输入的差异是什么?



输出参数



我尝试过:



为什么使用输出参数而不是返回值。



输出参数的优点是什么。输入和输出参数的差异是什么? class =h2_lin>解决方案

返回值只能返回一个对象 - 虽然它可以是包含其他类实例的类实例,但它仍然意味着你只能返回一个对象 - 所以如果你想要返回多个值,您必须创建一个容器类专门用于保存您想要返回到调用方法的数据,或者您需要使用 out ref 参数。

例如,假设您创建了一个设置文件打开对话框并让用户使用的方法为您选择一个文件。问题是你想知道用户是否按下取消...所以现在你需要返回两个项目:文件名和一个 bool 其中说用户选中此文件。为此,您需要返回两个不同的值,因此您可以创建一个容器类:

  public   class  FileReturn 
{
public string FileName;
public bool IsSelected;
}
...
public FileReturn SelectAFile()
{
FileReturn result = new FileReturn();
...
result.FileName = myOpenFileDialog.FileName;
result.IsSelected = true ;
返回结果;
}

但使用起来很麻烦:

  string 文件名; 
FileReturn fr = SelectAFile();
if (fr.IsSelected)
{
fileName = fr.FileName;
...



相反,您可以使用out参数返回文件名:

  public   bool  SelectAFile( out  fileName) 
{
...
fileName = myOpenFileDialog.FileName;
return true ;
}

然后使用起来更清晰:

  string  fileName ; 
if (SelectAFile( out fileName))
{
。 ..


why output parameters are used rather than return value.

what are the advantages of output parameters.what is the difference b/w input and

outputparameters

What I have tried:

why output parameters are used rather than return value.

what are the advantages of output parameters.what is the difference input and outputparameters

解决方案

An return value can return only one object - and while that can be a class instance containing other class instances, it still means you can only return one object - so if you want to return multiple values you either have to create a "container" class specifically to hold the data you want to return to the calling method, or you need to use out or ref parameters.
For example, suppose you create a method which sets up a File Open dialog and lets the user select a file for you. The problem is that you want to know if the user pressed cancel...so now you have two items you need to return: the file name and a bool which says "user selected this file". To do that, you need to return two distinct values, so you could create a container class:

public class FileReturn
   {
   public string FileName;
   public bool IsSelected;
   }
...
public FileReturn SelectAFile()
   {
   FileReturn result = new FileReturn();
   ...
   result.FileName = myOpenFileDialog.FileName;
   result.IsSelected = true;
   return result;
   }

But that is cumbersome to use:

string fileName;
FileReturn fr = SelectAFile();
if (fr.IsSelected)
   {
   fileName = fr.FileName;
   ...


Instead, you can use an out parameter to return the filename:

public bool SelectAFile(out fileName)
   {
   ...
   fileName =  myOpenFileDialog.FileName;
   return true;
   }

Then it's cleaner to use:

string fileName;
if (SelectAFile(out fileName))
   {
   ...


这篇关于为什么使用输出参数而不是返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆