如果内部方法也接受 C#7 中的 out 参数,为什么不能链接 ref 返回?

2024-01-15

我正在尝试 C#7 的新功能,发现了一些奇怪的东西。 给出以下简化场景:

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;
    }
}

为什么第二种方法会给我以下编译器错误?

CS8157  Cannot return 'cmd' by reference because it was initialized to a value that cannot be returned by reference

我知道编译器不允许您返回对 var 的引用,而该 var 稍后可能会死掉,但我真的不明白额外的输出参数如何以任何方式改变这种情况。


您不能调用具有 ref 或 out 参数的 ref 返回方法

这个改变可以修复它

public ref Command CreateCommandWithIndex(out int index)
        {
            ref Command cmd = ref cb.GetNextCommand(out index);
            return ref cmd;
        }

然后当你调用这个方法时按值调用它

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果内部方法也接受 C#7 中的 out 参数,为什么不能链接 ref 返回? 的相关文章

随机推荐