.NET中ref和out参数的区别是什么?在什么情况下,一个会比另一个更有用?一个可以使用而另一个不能使用的代码片段是什么?
当前回答
ref变量在传入之前需要初始化。 需要在函数实现中设置out变量 输出参数可以被认为是额外的返回变量(不是输入) Ref参数可以看作是输入变量和输出变量。
其他回答
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.
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;
}
Ref可能会在null时阻塞,因为它可能期望修改一个现有对象。Out需要null,因为它返回一个新对象。
在函数中不需要设置Ref形参,而out形参必须在退出函数之前绑定到一个值。传递出去的变量也可以在没有初始化的情况下传递给函数。
ref变量在传入之前需要初始化。 需要在函数实现中设置out变量 输出参数可以被认为是额外的返回变量(不是输入) Ref参数可以看作是输入变量和输出变量。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制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版本