问题
Coming from C++, returning a local variable was a bad idea (when allocated memory on the stack).
Now using C# I'm getting the impression it isn't a bad idea (when returning a value, not a reference).
Why is that? I understand C# uses the GC but I'm not sure what difference that would make in this case.
回答1:
The problem in C/C++ is that you can return a pointer to data that is located on the stack. If you do that the pointer is invalid as soon as the stack frame is destroyed. In managed C# you can't do such a thing.
Returning locals in C# is fine. If you return a value type, the value is copied. If you return a reference, the reference itself is copied (but it still points to the same object on the heap). In either case, there's no issue.
来源:https://stackoverflow.com/questions/22432584/c-sharp-returning-local-variables