当使用REF VS出来 [英] When to use ref vs out
问题描述
有人问我有一天当他们应该使用的参数关键字退出
而不是 REF
。虽然我(我认为)理解 REF之间的差异
和退出
关键字(即已<一个href=\"http://stackoverflow.com/questions/388464/c-whats-the-difference-between-the-ref-and-out-keywords\">asked 前),最好的解释似乎是, REF
== 在
和退出
,都有些什么(假设或code)的例子,我应该使用退出
,而不是 REF
。
Someone asked me the other day when they should use the parameter keyword out
instead of ref
. While I (I think) understand the difference between the ref
and out
keywords (that has been asked before) and the best explanation seems to be that ref
== in
and out
, what are some (hypothetical or code) examples where I should always use out
and not ref
.
由于 REF
较为一般,为什么你想使用退出
?难道只是语法糖?
Since ref
is more general, why do you ever want to use out
? Is it just syntactic sugar?
推荐答案
您应该使用退出
除非你需要 REF
。
You should use out
unless you need ref
.
它使一个很大的区别时,需要对数据进行编组例如另一个方法,其可以是昂贵的。所以,你想避免编组的初始值时,该方法不使用它。
It makes a big difference when the data needs to be marshalled e.g. to another process, which can be costly. So you want to avoid marshalling the initial value when the method doesn't make use of it.
除此之外,它也显示了声明或呼叫的读者的初始值是否是相关的(和潜在preserved),或扔掉。
Beyond that, it also shows the reader of the declaration or the call whether the initial value is relevant (and potentially preserved), or thrown away.
作为一个微小的差别,out参数需要不能被初始化。
As a minor difference, an out parameter needs not be initialized.
为示例了
:
string a, b;
person.GetBothNames(out a, out b);
,其中GetBothNames是原子检索两个值的方法,该方法不会改变行为的任何一个和b。如果调用去夏威夷的服务器,复制从这里到夏威夷的初始值是带宽的浪费。类似的片段使用REF:
where GetBothNames is a method to retrieve two values atomically, the method won't change behavior whatever a and b are. If the call goes to a server in Hawaii, copying the initial values from here to Hawaii is a waste of bandwidth. A similar snippet using ref:
string a = String.Empty, b = String.Empty;
person.GetBothNames(ref a, ref b);
可能混淆读者,因为它看起来像a和b的初始值是相关的(虽然方法名称将表明它们不是)。
could confuse readers, because it looks like the initial values of a and b are relevant (though the method name would indicate they are not).
为 REF示例
:
string name = textbox.Text;
bool didModify = validator.SuggestValidName(ref name);
下面的初始值是相关的方法
Here the initial value is relevant to the method.
这篇关于当使用REF VS出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!