passing in object by ref

天大地大妈咪最大 提交于 2020-01-11 09:52:11

问题


What is the difference between

public function Foo(ref Bar bar)
{
   bar.Prop = 1;
}

public function Foo(Bar bar)
{
   bar.Prop = 1;
}

essentially what is the point of "ref". isn't an object always by reference?


回答1:


The point is that you never actually pass an object. You pass a reference - and the argument itself can be passed by reference or value. They behave differently if you change the parameter value itself, e.g. setting it to null or to a different reference. With ref this change affects the caller's variable; without ref it was only a copy of the value which was passed, so the caller doesn't see any change to their variable.

See my article on argument passing for more details.




回答2:


Yes. But if you were to do this:

public function Foo(ref Bar bar)
{
   bar = new Bar();
}

public function Foo(Bar bar)
{
    bar = new Bar();
}

then you'd see the difference. The first passes a reference to the reference, and so in this case bar gets changed to your new object. In the second, it doesn't.



来源:https://stackoverflow.com/questions/729526/passing-in-object-by-ref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!