为什么我有时必须通过参考通过课程,而有时则不需要?

发布于 2024-11-30 18:02:24 字数 309 浏览 0 评论 0原文

我有一个采用 ListFoobar 作为参数的方法。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

霞映澄塘 2024-12-07 18:02:24

如果参数的值发生变化,如下所示:

parameter = new SomeValue();

那么调用者将使用ref看到该变化。

相反,如果您要更改调用者传递引用的对象的内容,则可以按值传递该引用

public void AppendHello(StringBuilder builder)
{
    // This changes the data within the StringBuilder object that the
    // builder variable refers to. It does *not* change the value of the
    // builder variable itself.
    builder.Append("Hello");
}

请参阅我的有关参数传递的文章了解更多信息。

请注意,如果参数类型是结构体而不是类,那么您将不会传递对象引用的副本 - 您将传递实际数据本身。在这种情况下,您还需要使用ref

If the value of a parameter change, like this:

parameter = new SomeValue();

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:

public void AppendHello(StringBuilder builder)
{
    // This changes the data within the StringBuilder object that the
    // builder variable refers to. It does *not* change the value of the
    // builder variable itself.
    builder.Append("Hello");
}

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.

那些过往 2024-12-07 18:02:24

你说的“修改”是什么意思?您可以将对象传递给方法并通过更改属性或将元素添加到通用列表来更改其数据。但是,您无法更改该变量指向的实际对象。为了真正改变,比如 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文