最佳实践:ref 参数还是返回值? [英] Best practice: ref parameter or return value?

查看:23
本文介绍了最佳实践:ref 参数还是返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其实我在做一个列表作为参考参数如下:

Actually I am doing a list as a reference parameter as follows:

public static List ListMethod(List result)

我也看到有些人这样做:

I saw some people doing in this way too:

public static void ListMethod(ref List result)

如果我没记错的话,"my" 方法也将 list 作为参考参数,你应该可以像 "other" 在他的方法中那样使用它.

If I'm not wrong, "my" method also takes the list as reference parameter, and you should be able to use it just the same way as "other" does in his method.

但对我来说,输入一个参数,用它做一些事情并在方法返回值中返回它,对我来说似乎更干净".

But it seems more "clean" to me that you enter a parameter, do something with it and return it in the methods return value.

有什么好的论据支持或反对一种方法或另一种方法?

Any good arguments for or against one method or the other?

推荐答案

很可能您不需要使用 ref - 但 有区别.

It's likely that you don't need to use ref - but there is a difference.

通常当我看到人们使用 ref 作为引用类型参数时,那是因为他们不了解参数传递的工作原理.但是如果你的方法有这样的东西:

Usually when I see people using ref for reference type parameters, it's because they don't understand how parameter passing works. But if your method has something like this:

result = new List();
...

那么在第一种情况下,调用者不会看到更改,而在第二种情况下,调用者的变量将被更改以引用新对象.

then in the first case the caller won't see the change, whereas in the second case the caller's variable will be changed to refer to the new object.

查看我的关于参数传递的文章了解更多详情.

See my article on parameter passing for a lot more detail.

这篇关于最佳实践:ref 参数还是返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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