何时使用in vs ref vs out [英] When to use in vs ref vs out

查看:90
本文介绍了何时使用in vs ref vs out的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天有人问我应该使用参数关键字 out 而不是 ref 。虽然我(我认为)了解 ref out 关键字之间的区别(这一直是问及),最好的解释似乎是 ref == in out ,有一些(假设的或代码)示例中,我应该始终使用 out 而不是 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 更笼统,为什么您要使用 out

Since ref is more general, why do you ever want to use out? Is it just syntactic sugar?

推荐答案

您应该使用 out 除非您是语法糖?需要 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.

除此之外,它还向声明的读者或调用者显示是否

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.

out 的示例:

string a, b;
person.GetBothNames(out a, out b);

其中GetBothNames是一种原子地检索两个值的方法,该方法不会改变行为,无论a和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.

这篇关于何时使用in vs ref vs out的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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