[英]C# return struct reference from method
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. 在C ++中,返回方法中分配给堆栈的对象的引用会产生垃圾值,原因是该方法离开作用域后,堆栈对象被破坏。 Given that in C# structs are allocated on the stack, would this yield garbage values as well? 假设在C#中将结构分配到堆栈上,这还会产生垃圾值吗?
struct Test
{
//data
}
Test Foo()
{
Test t1 = new Test();
return t1;
}
I think you should read this: http://mustoverride.com/ref-returns-and-locals/ 我认为您应该阅读以下内容: http : //mustoverride.com/ref-returns-and-locals/
In short, the C# Design team decided to disallow returning local variables by reference. 简而言之,C#设计团队决定禁止通过引用返回局部变量。
– Disallow returning local variables by reference. –禁止通过引用返回局部变量。 This is the solution that was chosen for C#. 这是为C#选择的解决方案。 - To guarantee that a reference does not outlive the referenced variable C# does not allow returning references to local variables by reference. -为了确保引用不会超出引用变量的作用,C#不允许通过引用将引用返回给局部变量。 Interestingly, this is the same approach used by Rust, although for slightly different reasons. 有趣的是,尽管原因略有不同,这与Rust使用的方法相同。 (Rust is a RAII language and actively destroys locals when exiting scopes) (Rust是一种RAII语言,在退出范围时会主动摧毁本地人)
Even with the ref
keyword, if you go ahead and try this: 即使使用ref
关键字,也可以尝试以下操作:
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: 您将看到编译器出现以下错误:
Cannot return local 'test' by reference because it is not a ref local 无法通过引用返回本地“测试”,因为它不是本地引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.