问题
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.
回答1:
you can't call ref return method that has ref or out param
this change can be fix it
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
来源:https://stackoverflow.com/questions/45929614/why-its-not-possible-to-chain-ref-returns-if-the-inner-method-also-accepts-out