4

更新所以完全拉了一个工具时刻。我真正的意思是参考与输出/参考。任何说“参考”的东西,我真正的意思是参考,如

一些方法(对象一些对象)

相对

SomeMethod(out someObject)

对不起。只是不想更改代码,因此答案已经有意义。

据我了解,与 ref 不同,它“复制”指针并在堆栈上创建一个新空间以使用该指针,但不会更改指针:

SomeMethod()
{
 SomeThing outer = new SomeThing();
 RefMethod(ref outer)
}

RefMethod(ref inner)  //new space on stack created and uses same pointer as outer
{
   inner.Hi = "There"; //updated the object being pointed to by outer
   inner = new SomeThing();//Given a new pointer, no longer shares pointer with outer
                           //New object on the heap
}

Out 复制指针并可以操纵它指向的位置:

SomeMethod()
{
 SomeThing outer = new SomeThing();
 RefMethod(out outer)
}

RefMethod(out inner)  //same pointer shared
{

   inner = new SomeThing();//pointer now points to new place on heap  
                           //outer now points to new object
                           //Old object is orphaned if nothing else points to it
}

对对象来说这很好而且很花哨,但是值类型怎么办,因为它们没有任何东西指向仅在堆栈上?

4

3 回答 3

9

仅仅因为变量存在于堆栈中(如果它是局部变量)并不意味着您不能创建指向它的指针——事实上引用类型也是如此。

RefMethod 中的指针指向“外部”变量 - 变量本身存在于堆栈中,因为它是一个未捕获的局部变量。

正如 Leppie 所说, ref 和 out 除了明确分配的规则外是相同的 - 事实上,IL 中唯一的区别是应用于 out 参数的属性。

有关 ref/out 的更多详细信息,请参阅我关于参数传递的文章。

于 2009-01-12T19:52:45.607 回答
3

据我所知, ref 和 out 完全相同,只是无法初始化 out 参数。因此两者都进入堆栈。

于 2009-01-12T19:52:22.003 回答
1

实际上在引用类型上使用 ref 或 out 也会创建一个指针……不是指向对象,而是指向对象的引用!所以这将是某种

RefMethod(SomeThing **inner)
{
}

在 C++ 中,而对于值类型,它会是

RefMethod2(int *inner)
{
}

对于值类型。

于 2009-01-12T20:40:08.617 回答