c#中out参数的作用是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1165105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:45:57  来源:igfitidea点击:

what is use of out parameter in c#

c#.netparameters

提问by

Can you please tell me what is the exact use of outparameter?

你能告诉我out参数的确切用途是什么吗?

Related Question:
What is the difference between ref and out? (C#)

相关问题:
ref 和 out 有什么区别?(C#)

回答by rahul

http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

Out parameters are output only parameters meaning they can only passback a value from a function.We create a "out" parameter by preceding the parameter data type with the out modifier. When ever a "out" parameter is passed only an unassigned reference is passed to the function.

Out 参数是仅输出参数,这意味着它们只能从函数中传回一个值。我们通过在参数数据类型前面加上 out 修饰符来创建“out”参数。当传递“out”参数时,只会将未分配的引用传递给函数。

using System;
class ParameterTest
{
 static void Mymethod(out int Param1)
 {
  Param1=100;
 }
 static void Main()
 {
  int Myvalue=5;
  MyMethod(Myvalue);
  Console.WriteLine(out Myvalue);             
 }
}

Output of the above program would be 100 since the value of the "out" parameter is passed back to the calling part. Note

由于“out”参数的值被传递回调用部分,因此上述程序的输出将为 100。笔记

The modifier "out" should precede the parameter being passed even in the calling part. "out" parameters cannot be used within the function before assigning a value to it. A value should be assigned to the "out" parameter before the method returns.

即使在调用部分,修饰符“out”也应该在传递的参数之前。在给函数赋值之前,不能在函数中使用“out”参数。在方法返回之前,应该为“out”参数分配一个值。

回答by Kirtan

The out method parameter keyword on a method parameter causes a method to refer to the same variable that was passed into the method. Any changes made to the parameter in the method will be reflected in that variable when control passes back to the calling method.

Declaring an out method is useful when you want a method to return multiple values. A method that uses an out parameter can still return a value. A method can have more than one out parameter.

To use an out parameter, the argument must explicitly be passed to the method as an out argument. The value of an out argument will not be passed to the out parameter.

A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.

方法参数上的 out 方法参数关键字会导致方法引用传递给该方法的相同变量。当控制权返回给调用方法时,对方法中参数所做的任何更改都将反映在该变量中。

当您希望一个方法返回多个值时,声明一个 out 方法很有用。使用 out 参数的方法仍然可以返回一个值。一个方法可以有多个输出参数。

要使用 out 参数,该参数必须作为 out 参数显式传递给方法。out 参数的值不会传递给 out 参数。

作为输出参数传递的变量不需要初始化。但是,必须在方法返回之前为 out 参数分配一个值。

An Example:

一个例子:

using System;
public class MyClass 
{
   public static int TestOut(out char i) 
   {
      i = 'b';
      return -1;
   }

   public static void Main() 
   {
      char i;   // variable need not be initialized
      Console.WriteLine(TestOut(out i));
      Console.WriteLine(i);
   }
}

回答by Steven Sudit

The typical use case is a method that needs to return more than one thing, so it can't just use the return value. Commonly, the return value is used for a success flag while the outparameter(s) sets values when the method is successful.

典型的用例是一个方法需要返回多个东西,所以它不能只使用返回值。通常,返回值用于成功标志,而out参数在方法成功时设置值。

The classic example is:

经典的例子是:

public bool TryGet( 
   string key,
   out string value
)

If it returns true, then value is set. Otherwise, it's not. This lets you write code such as:

如果返回 true,则设置 value。否则,它不是。这使您可以编写代码,例如:

string value;
if (!lookupDictionary.TryGet("some key", out value))
  value = "default";

Note that this doesn't require you to call Contains before using an indexer, which makes it faster and cleaner. I should also add that, unlike the very similar refmodifier, the compiler won't complain if the outparameter was never initialized.

请注意,这不需要您在使用索引器之前调用 Contains,这会使其更快、更清晰。我还应该补充一点,与非常相似的ref修饰符不同,如果out参数从未初始化,编译器不会抱怨。

回答by EPiddy

from http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

来自http://msdn.microsoft.com/en-us/vcsharp/aa336814.aspx

One way to think of out parameters is that they are like additional return values of a method. They are very convenient when a method returns more than one value, in this example firstName and lastName. Out parameters can be abused however. As a matter of good programming style if you find yourself writing a method with many out parameters then you should think about refactoring your code. One possible solution is to package all the return values into a single struct.

考虑 out 参数的一种方法是它们就像方法的附加返回值。当一个方法返回多个值时,它们非常方便,在本例中为 firstName 和 lastName。但是,可以滥用输出参数。作为良好的编程风格,如果您发现自己编写的方法带有许多输出参数,那么您应该考虑重构您的代码。一种可能的解决方案是将所有返回值打包到一个结构中。

In contrast ref parameters are considered initially assigned by the callee. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.

相反, ref 参数被认为是由被调用者最初分配的。因此,被调用者不需要在使用前分配给 ref 参数。Ref 参数传入和传出方法。

回答by jjnguy

The best example of a good use of an outparameter are in the TryParsemethods.

充分利用out参数的最佳示例是TryParse方法。

int result =-1;
if (!Int32.TryParse(SomeString, out result){
    // log bad input
}

return result;

Using TryParseinstead of ParseIntremoves the need to handle exceptions and makes the code much more elegant.

使用TryParse而不是ParseInt消除处理异常的需要并使代码更加优雅。

The outparameter essentially allows for more than one return values from a method.

out参数基本上允许一个方法有多个返回值。

回答by Timothy Carter

Jon Skeet describes the different ways of passing parameters in great detail in thisarticle. In short, an out parameter is a parameter that is passed uninitialized to a method. That method is then required to initialize the parameter before any possible return.

乔恩斯基特介绍的很详细参数传递方式的不同,这个文章。简而言之,out 参数是未初始化传递给方法的参数。然后需要该方法在任何可能的返回之前初始化参数。

回答by Edwin Tai

generally we cannot get the variables inside a function if we don't get by a return value. but use keyword "out" we can change it value by a function.

如果我们不通过返回值获取,通常我们无法获取函数内部的变量。但是使用关键字“out”我们可以通过函数改变它的值。

回答by JulianR

Besides allowing you to have multiple return values, another use is to reduce overhead when copying a large value type to a method. When you pass something to a method, a copy of the value of that something is made. If it's a reference type (string for example) then a copy of the reference (the value of a reference type) is made. However, when you copy a value type (a structlike intor double) a copy of the entire thing is made (the value of a value typeis the thing itself). Now, a reference is 4 bytes (on 32-bit applications) and an intis 4 bytes, so the copying is not a problem. However, it's possible to have very large value types and while that's not recommended, it might be needed sometimes. And when you have a value type of say, 64 bytes, the cost of copying it to methods is prohibitive (especially when you use such a large structfor performance reasons in the first place). When you use out, no copy of the object is made, you simply refer to the same thing.

除了允许您有多个返回值之外,另一个用途是减少将大值类型复制到方法时的开销。当您将某些内容传递给方法时,会创建该内容的值的副本。如果它是引用类型(例如字符串),则生成引用的副本(引用类型的值)。但是,当您复制值类型(a structlikeintdouble)时,会生成整个事物的副本(值类型是事物本身)。现在,一个引用是 4 个字节(在 32 位应用程序上)和一个int是4个字节,所以复制不是问题。但是,可能有非常大的值类型,虽然不推荐这样做,但有时可能需要。当你有一个 64 字节的值类型时,将它复制到方法的成本是令人望而却步的(尤其是当你struct首先出于性能原因使用如此大的值时)。当您使用 时out,不会制作对象的副本,您只需引用相同的内容。

public struct BigStruct
{
  public int A, B, C, D, E, F, G, H, J, J, K, L, M, N, O, P;
}

SomeMethod(instanceOfBigStruct); // A copy is made of this 64-byte struct.

SomeOtherMethod(out instanceOfBigStruct); // No copy is made

A second use directly in line with this is that, because you don't make a copy of the struct, but refer to the samething in the method as you do outside of the method, any changes made to the object inside the method, are persisted outside the method. This is already the case in a reference type, but not in value types.

与此直接相符的第二个用途是,因为您不复制结构,而是在方法中引用在方法外所做的相同的事情,对方法内的对象所做的任何更改,在方法之外持久化。这在引用类型中已经是这种情况,但在值类型中则不然。

Some examples:

一些例子:

 public void ReferenceExample(SomeReferenceType s)
 {
   s.SomeProperty = "a string"; // The change is persisted to outside of the method
 }

 public void ValueTypeExample(BigStruct b)
 {
   b.A = 5; // Has no effect on the original BigStruct that you passed into the method, because b is a copy!
 }

 public void ValueTypeExampleOut(out BigStruct b)
 {
   b = new BigStruct();
   b.A = 5; // Works, because you refer to the same thing here
 }

Now, you may have noticed that inside ValueTypeExampleOutI made a newinstance of BigStruct. That is because, if you use out, you mustassign the variable to something before you exit the method.

现在,你可能已经注意到这里面ValueTypeExampleOut我做了一个new实例BigStruct。那是因为,如果使用out,则必须在退出方法之前将变量分配给某些东西。

There is however, another keyword, refwhich is identical except that you are not forced to assign it within the method. However, that also means you can't pass in an unassigned variable, which would make that nice Try.. pattern not compile when used with ref.

但是,还有另一个关键字,ref它是相同的,只是您不必在方法中分配它。然而,这也意味着你不能传入一个未赋值的变量,这会使 Try.. 模式在与ref.

int a;
if(TrySomething(out a)) {}

That works because TrySomethingis forced to assign something to a.

之所以有效,TrySomething是因为被迫将某些内容分配给a.

int a;
if(TrySomething(ref a)) {} 

This won't work because ais unassigned (just declared) and refrequires that you only use it with an assigned variable.

这将不起作用,因为a未分配(刚刚声明)并且ref要求您仅将其与分配的变量一起使用。

This works because ais assigned:

这是有效的,因为a已分配:

int a = 0;
if(TrySomething(ref a)) {}

However, in both cases (refand out) any changes made to awithin the TrySomethingmethod are persisted to a.

但是,在这两种情况下 (refout)aTrySomething方法内所做的任何更改都保留到a.

As I already said, changes made to a reference typeare persisted outside the method in which you make them, because through the reference, you refer to the same thing.

正如我已经说过的,对引用类型所做的更改会在您创建它们的方法之外持久化,因为通过引用,您指的是同一件事。

However, this doesn't do anything:

但是,这没有任何作用:

public void Example(SomeReferenceType s)
{
  s = null;
}

Here, you just set the copyof a reference to sto null, which only exists within the scope of the method. It has zero effect on whatever you passed into the method.

在这里,您只需将引用的副本设置s为 null,它只存在于方法的范围内。它对您传递给方法的任何内容的影响为零。

If you want to do this, for whatever reason, use this:

如果您想这样做,无论出于何种原因,请使用以下命令:

public void Example1(ref SomeReferenceType s)
{
  s = null; // Sets whatever you passed into the method to null
}

I think this covers all use-cases of outand ref.

我认为这涵盖了out和 的所有用例ref

回答by Abhishek Chevdawala

In simple words pass any variable to the function by reference so that any changes made to that variable in side that function will be persistent when function returns from execution.

简而言之,通过引用将任何变量传递给函数,以便在函数执行返回时对该函数中的变量所做的任何更改都将保持不变。