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

查看:293
本文介绍了最佳实践: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)

如果我没有错,我的方法还接受了列表作为基准参数,你应该能够使用它用同样的方法为其他确实在他的方法。

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.

请参阅我article上传递了很多更详细的参数。

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

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

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