开发者

Ref C# - new assignment in foo, propagates to other functions using same reference?

My basic question is asking if I change the reference of a ref in one method is it reflected in the other method (like double pointers in C++)?

method()
{
  referenceTypeInt t = new t(1);
  asyncCall foo(ref t);
  bar(ref t);
}

foo(ref a)
开发者_高级运维{
  a = new t(3);
}
bar (ref a)
{
  wait for 10 seconds/until foo finishes;
  Console.print ("t is" t.ToString())
}

The above is rough Pseudoish code, but would t be 3 above?


That's how ref works, in general.

However, there may be one point here that's bad. I'm not sure if this:

asyncCall foo(ref t);

Was meant to be pseudo code for the new Async CTP (in which case, it should be await foo(ref t);). If that was meant to be an async method call using the new async/await syntax, this won't work. ref and out parameters are not supported in async methods (similar to how they are not supported in iterators).


Yes, that's the point of ref. It indicates that the parameter should be treated as an alias to the variable, so assigning to it will alter the the variable itself. Since you ref again in bar, you have another alias, so the change reflected in the output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜