为什么我有时必须通过参考通过课程,而有时则不需要?
我有一个采用 List
和 Foobar
作为参数的方法。 Foobar 是一个常规类,具有私有变量、构造函数和对数据进行操作的方法。
我修改了方法中传递的两个实例,但由于某种原因,我必须使用 ref 关键字传递 Foobar,否则在方法完成时更改不会保留。我不必为列表执行此操作。
我最近在编程中多次注意到这一点。通常,当将类的实例传递给方法时,修改它会更改实例,但有时不会,并且需要 ref
关键字才能保留更改。它工作时看起来相当随机。有谁知道这是为什么?
I have a method that takes List<Foobar>
and Foobar
as parameters. Foobar is a regular class with private variables, a constructor, and methods to operate on the data.
I modify both of the instances passed in the method but for some reason I have to pass Foobar with the ref
keyword or else the changes do not stick when the method completes. I do not have to do this for the list.
I've noticed this a couple times recently in my programming. Usually when passing an instance of a class to the method, modifying it changes the instance, but sometimes it doesn't and it requires the ref
keyword for changes to stick. It seems rather random in when it works. Does anyone know why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果参数的值发生变化,如下所示:
那么调用者将仅使用
ref
看到该变化。相反,如果您要更改调用者传递引用的对象的内容,则可以按值传递该引用:
请参阅我的有关参数传递的文章了解更多信息。
请注意,如果参数类型是结构体而不是类,那么您将不会传递对象引用的副本 - 您将传递实际数据本身。在这种情况下,您还需要使用
ref
。If the value of a parameter change, like this:
then that change will only be seen by the caller using
ref
.If instead you're changing the contents of an object which the caller passed a reference to, then that reference can be passed by value:
See my article on parameter passing for more information.
Note that if the parameter type is a struct instead of a class, then you won't be passing a copy of the reference to an object - you'll be passing the actual data itself. In that situation you'd need to use
ref
as well.你说的“修改”是什么意思?您可以将对象传递给方法并通过更改属性或将元素添加到通用列表来更改其数据。但是,您无法更改该变量指向的实际对象。为了真正改变,比如 Foobar 完全改变,它需要通过 ref 传递。
What do you mean by "modifying it". You can pass an object to a method and change its data, either by changing properties or adding elements to a generic list. However, you cannot change the actual object pointed to by that variable. In order to actually change, say Foobar to something else entirely, it needs to be passed by ref.