Why it's not possible to chain ref returns if the inner method also accepts out params in C#7?

…衆ロ難τιáo~ 提交于 2021-02-06 10:51:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!