“var”之间有什么区别?和“出”参数? [英] What's the difference between "var" and "out" parameters?

查看:146
本文介绍了“var”之间有什么区别?和“出”参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 var 声明的参数与使用 out 声明的参数有什么区别?编译器如何对待它们有所不同(例如,通过生成不同的代码,或者通过更改哪个诊断程序发生)?或者不同的修饰符只允许程序员记录参数的预期用途?参数的类型对此有什么影响?

What's the difference between parameters declared with var and those declared with out? How does the compiler treat them differently (e.g., by generating different code, or by changing which diagnostics it issues)? Or do the different modifiers merely allow the programmer to document intended use of the parameters? What effect do the types of the parameters have on the matter?

推荐答案

A var 参数将被引用传递,就是这样。

A var parameter will be passed by reference, and that's it.

out 参数也通过引用传递,但是假定输入值是无关紧要的。对于托管类型(字符串,接口等),编译器将通过在例程开始之前清除变量来执行此操作,相当于写入 param:= nil 。对于非托管类型,编译器实现 out var 相同。

An out parameter is also passed by reference, but it's assumed that the input value is irrelevant. For managed types, (strings, Interfaces, etc,) the compiler will enforce this, by clearing the variable before the routine begins, equivalent to writing param := nil. For unmanaged types, the compiler implements out identically to var.

请注意,在调用站点执行托管参数的清除,因此为函数生成的代码不会随 out var 参数。

Note that the clearing of a managed parameter is performed at the call-site and so the code generated for the function does not vary with out or var parameters.

这篇关于“var”之间有什么区别?和“出”参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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