“var"和“var"有什么区别?和“出"参数? [英] What's the difference between "var" and "out" parameters?
问题描述
用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?
推荐答案
var
参数将通过引用传递,仅此而已.
A var
parameter will be passed by reference, and that's it.
out
参数也通过引用传递,但假定输入值无关紧要.对于托管类型(字符串、接口等),编译器将通过在例程开始之前清除变量来强制执行此操作,相当于编写 param := nil
.对于非托管类型,编译器以与 var
相同的方式实现 out
.
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"和“var"有什么区别?和“出"参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!