C#从方法返回结构引用 [英] C# return struct reference from method
问题描述
在 C++ 中,返回在方法中分配在堆栈上的对象的引用会产生垃圾值,因为一旦方法离开作用域,堆栈对象就会被销毁.鉴于在 C# 中结构是在堆栈上分配的,这也会产生垃圾值吗?
In C++, returning a reference of an object allocated on the stack in a method, yields garbage values due to the fact, that the stack object is destroyed as soon the method leaves the scope. Given that in C# structs are allocated on the stack, would this yield garbage values as well?
struct Test
{
//data
}
Test Foo()
{
Test t1 = new Test();
return t1;
}
推荐答案
我认为您应该阅读以下内容:http://mustoverride.com/ref-returns-and-locals/
I think you should read this: http://mustoverride.com/ref-returns-and-locals/
简而言之,C# 设计团队决定禁止通过引用返回局部变量.
In short, the C# Design team decided to disallow returning local variables by reference.
– 禁止通过引用返回局部变量.这是为 C# 选择的解决方案.- 保证引用确实不超过引用的变量 C# 不允许返回通过引用引用局部变量.有趣的是,这是Rust 使用的相同方法,尽管原因略有不同.(Rust 是一种 RAII 语言,退出时会主动销毁本地人范围)
– Disallow returning local variables by reference. This is the solution that was chosen for C#. - To guarantee that a reference does not outlive the referenced variable C# does not allow returning references to local variables by reference. Interestingly, this is the same approach used by Rust, although for slightly different reasons. (Rust is a RAII language and actively destroys locals when exiting scopes)
即使使用 ref
关键字,如果您继续尝试:
Even with the ref
keyword, if you go ahead and try this:
public struct Test
{
public int a;
}
public ref Test GetValueByRef()
{
var test = new Test();
return ref test;
}
您将看到编译器出现以下错误:
You will see that the compiler errors out with the following:
不能通过引用返回本地test",因为它不是本地引用
Cannot return local 'test' by reference because it is not a ref local
这篇关于C#从方法返回结构引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!