自修改对象的 Ref 与 No Ref

发布于 2024-12-11 17:04:09 字数 187 浏览 0 评论 0原文

如果在函数中修改作为参数引用的对象,是否使用 ref 有关系吗?下面两个函数有区别吗?

void DisposeObject(ClassThing c)
{
   c.Dispose();
}

void DisposeObject(ref ClassThing c)
{
   c.Dispose();
}

If the object being referenced as a parameter is being modified in a function, does it matter if you use ref or not? Is there a difference between the following two functions?

void DisposeObject(ClassThing c)
{
   c.Dispose();
}

void DisposeObject(ref ClassThing c)
{
   c.Dispose();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

煞人兵器 2024-12-18 17:04:09

没关系。重要的是,如果您要向 c 分配某些内容(并希望它反映在方法之外):

c = new ClassThing();

在这种情况下,您将使用 参考

It doesn't matter. What matters is if you're assigning something to c (and want it reflected outside the method):

c = new ClassThing();

In that case you'd use ref.

混吃等死 2024-12-18 17:04:09

这并不取决于你的情况。

但是:

如果您使用 ref 关键字传递引用对象,则可以在方法内部更改引用以指向此类型的另一个对象(因此它将在方法外部可见)

It doesnt depend in your case.

BUT:

if you pass a reference object with the ref keyword you have inside of the method the possibility to change the reference to point to another Object of this type (so it will be visible outside of the method)

落日海湾 2024-12-18 17:04:09

根据传递引用类型参数的 MSDN 指南

当按值传递引用类型参数时,可以更改引用指向的数据,例如类成员的值。但是,您无法更改引用本身的值;也就是说,您不能使用相同的引用为新类分配内存并使其保留在块之外。为此,请使用 ref 或 out 关键字传递参数。

因此,您可以更改原始对象,但无法更改原始对象以引用内存中的不同位置。示例:

static void Main()
{
    int[] integerArray = new int[8];
    foo(integerArray);
}

private void foo(int[] myArray)
{
    myArray[0] = 5;  //this changes integerArray
    myArray = new int[4]; //this does not change integerArray,
                          // ... but it would if you used ref or out
}

所以差异确实很重要,尽管我不具体了解 Dispose() 的行为。

According to the MSDN guide to passing reference-type parameters:

When you pass a reference-type parameter by value, it is possible to change the data pointed to by the reference, such as the value of a class member. However, you cannot change the value of the reference itself; that is, you cannot use the same reference to allocate memory for a new class and have it persist outside the block. To do that, pass the parameter using the ref or out keyword.

So you can alter the original object, but you cannot change the original object to reference a different location in memory. Example:

static void Main()
{
    int[] integerArray = new int[8];
    foo(integerArray);
}

private void foo(int[] myArray)
{
    myArray[0] = 5;  //this changes integerArray
    myArray = new int[4]; //this does not change integerArray,
                          // ... but it would if you used ref or out
}

So the difference does matter, although I don't know specifically about the behavior of Dispose().

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