.NET中ref和out参数的区别是什么?在什么情况下,一个会比另一个更有用?一个可以使用而另一个不能使用的代码片段是什么?
当前回答
out:
在c#中,一个方法只能返回一个值。如果希望返回多个值,可以使用out关键字。out修饰符返回为引用返回。最简单的答案是使用关键字“out”从方法中获取值。
您不需要在调用函数中初始化该值。 必须在被调用的函数中赋值,否则编译器将报错。
ref:
在c#中,当你将一个值类型,如int, float, double等作为参数传递给方法参数时,它是按值传递的。因此,如果修改形参值,它不会影响方法调用中的实参。但是,如果您用“ref”关键字标记参数,它将反映在实际的变量中。
在调用函数之前,需要初始化变量。 为方法中的ref参数赋值不是强制的。如果不更改值,为什么需要将其标记为“ref”?
其他回答
它们几乎是一样的-唯一的区别是,作为out形参传递的变量不需要初始化,但作为ref形参传递的变量必须设置为某个值。
int x;
Foo(out x); // OK
int y;
Foo(ref y); // Error: y should be initialized before calling the method
Ref形参用于可能被修改的数据,out形参用于已经使用返回值的函数(例如int.TryParse)的额外输出数据。
Out参数由调用的方法初始化,ref参数在调用方法之前初始化。因此,当您只需要获得第二个返回值时,使用out参数,ref参数用于获取一个值并可能返回对该值的更改(次于主返回值)。
Out和ref是完全相同的,除了Out变量在发送到深渊之前不需要初始化。我没有那么聪明,我从MSDN库抄袭了:)。
然而,更明确地说,修饰符的含义是,如果您在代码中更改了该变量的引用,out和ref将导致调用变量也更改引用。在下面的代码中,一旦newGuy从doStuff调用中返回,ceo变量将是它的引用。如果不是为了ref(或out),引用就不会被改变。
private void newEmployee()
{
Person ceo = Person.FindCEO();
doStuff(ref ceo);
}
private void doStuff(ref Person employee)
{
Person newGuy = new Person();
employee = newGuy;
}
An out parameter is a ref parameter with a special Out() attribute added. If a parameter to a C# method is declared as out, the compiler will require that the parameter be written before it can be read and before the method can return. If C# calls a method whose parameter includes an Out() attribute, the compiler will, for purposes of deciding whether to report "undefined variable" errors, pretend that the variable is written immediately before calling the method. Note that because other .net languages do not attach the same meaning to the Out() attribute, it is possible that calling a routine with an out parameter will leave the variable in question unaffected. If a variable is used as an out parameter before it is definitely assigned, the C# compiler will generate code to ensure that it gets cleared at some point before it is used, but if such a variable leaves and re-enters scope, there's no guarantee that it will be cleared again.
为什么c#中有“ref”和“out”?
带有out形参的方法的调用者不需要在调用之前赋值给作为out形参传递的变量;但是,被调用方需要在返回之前赋值给out形参。
相反,ref参数被认为是由调用者最初分配的。因此,被调用方在使用前不需要赋值给ref参数。Ref参数同时传入和传出方法。
out是out的意思,而ref是in和out的意思。
这些参数与COM接口的[out]和[in,out]参数密切对应,out参数的优点是,在被调用的方法不需要预分配对象的情况下,调用者不需要传递预分配对象——这避免了分配的成本,以及可能与封送相关的任何成本(更可能在COM中,但在. net中并不少见)。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何在iis7应用程序池中设置。net Framework 4.5版本