c# - 我应该使用“ref”吗?通过引用方法传递集合(例如列表)?
我应该使用“ref”通过引用方法来传递列表变量吗?
答案是否不需要“ref”(因为列表将是引用变量),但是为了便于阅读,将“ref”放入?
Should I use "ref" to pass a list variable by reference to a method?
Is the answer that "ref" is not needed (as the list would be a reference variable), however for ease in readability put the "ref" in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
字典是引用类型,因此不可能按值传递,尽管对字典的引用是值。让我尝试澄清这一点:
A dictionary is a reference type, so it is not possible to pass by value, although references to a dictionary are values. Let me try to clear this up:
不,不要使用 ref ,除非您想更改变量引用的列表。如果您只想访问列表,请不使用 ref 进行操作。
如果您创建参数引用,则表示调用者应该期望他们传入的参数可以分配给另一个对象。如果你不这样做,那么它就没有传达正确的信息。您应该假设所有 C# 开发人员都了解传入的对象引用。
No, don't use a ref unless you want to change what list the variable is referencing. If you want to just access the list, do it without ref.
If you make a parameter ref, you are saying that the caller should expect that the parameter they pass in could be assigned to another object. If you aren't doing that, then it's not conveying the correct information. You should assume that all C# developers understand that an object reference is being passed in.
您的场景中不需要 ref ,它也不会提高可读性。
仅当您打算更改变量引用的内容而不是其引用的对象的内容时,才使用 ref 。这有道理吗?
You don't need
ref
in your scenario, nor will it help with readability.ref
is only used if you intend to change what the variable references to, not the contents of the object it references. Does that make sense?