如果内部方法也接受 C#7 中的 out 参数,为什么不能链接 ref 返回? [英] Why it's not possible to chain ref returns if the inner method also accepts out params in C#7?
本文介绍了如果内部方法也接受 C#7 中的 out 参数,为什么不能链接 ref 返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试新的 C#7 特性时发现了一些奇怪的东西.鉴于以下简化场景:
I was experimenting with the new C#7 features and I found something strange. Given the following simplified scenario:
public struct Command
{
}
public class CommandBuffer
{
private Command[] commands = new Command[1024];
private int count;
public ref Command GetNextCommand()
{
return ref commands[count++];
}
public ref Command GetNextCommand(out int index)
{
index = count++;
return ref commands[index];
}
}
public class BufferWrapper
{
private CommandBuffer cb = new CommandBuffer();
// this compiles fine
public ref Command CreateCommand()
{
ref Command cmd = ref cb.GetNextCommand();
return ref cmd;
}
// doesn't compile
public ref Command CreateCommandWithIndex()
{
ref Command cmd = ref cb.GetNextCommand(out int index);
return ref cmd;
}
}
为什么第二种方法给我以下编译器错误?
Why does the second method give me the following compiler error?
CS8157 Cannot return 'cmd' by reference because it was initialized to a value that cannot be returned by reference
我知道编译器不能允许你返回一个变量的引用,这个变量可能会在以后死掉,但我真的不知道有一个额外的输出参数会如何以任何方式改变这种情况.
I know the compiler can't allow you to return a ref to a var that could end up being dead later on, but I don't really see how having an additional out param changes this scenario in any way.
推荐答案
不能调用带有 ref 或 out 参数的 ref 返回方法
you can't call ref return method that has ref or out param
这个改动可以修复它
public ref Command CreateCommandWithIndex(out int index)
{
ref Command cmd = ref cb.GetNextCommand(out index);
return ref cmd;
}
然后当你调用这个方法时按值调用它
then when you call this method call it by value
这篇关于如果内部方法也接受 C#7 中的 out 参数,为什么不能链接 ref 返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文