C#返回局部变量 [英] C# Returning local variables
问题描述
来自C ++,返回局部变量是个坏主意(在堆栈上分配内存时).
Coming from C++, returning a local variable was a bad idea (when allocated memory on the stack).
现在使用C#的印象是,这不是一个坏主意(返回值而不是引用时).
Now using C# I'm getting the impression it isn't a bad idea (when returning a value, not a reference).
那是为什么?我知道C#使用GC,但是我不确定在这种情况下会有什么区别.
Why is that? I understand C# uses the GC but I'm not sure what difference that would make in this case.
推荐答案
C/C ++中的问题是您可以返回指向堆栈上数据的指针.如果这样做,则一旦堆栈帧被破坏,指针就无效.在托管C#中,您无法执行此操作.
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.
使用C#返回本地人很好.如果返回值类型,则将复制该值.如果返回引用,则引用本身将被复制(但仍指向堆上的同一对象).无论哪种情况,都没有问题.
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.
这篇关于C#返回局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!