C#Out参数问题:Out如何处理值类型?

Pro*_*ool 4 c# heap stack out-parameters

更新所以完全拉动了一个工具时刻.我的意思是参考与Out/Ref.任何说"参考"的东西我的意思都是参考

SomeMethod(Object someObject)

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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

这对于对象来说很好用,但是看到的是值类型,因为它们没有任何东西可以指向只在堆栈中?

Jon*_*eet 9

仅仅因为变量存在于堆栈上(如果它是局部变量)并不意味着你不能创建指向它的指针 - 实际上也是引用类型的情况.

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

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

有关参考传递的更多详细信息,请参阅我关于参数传递的文章.