首页 > 解决方案 > out 参数在 C# 中不起作用。为什么?

问题描述

out参数在 C# 中不起作用。为什么?

这是我的代码:

using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var hashSet = new HashSet<int>(2);
        Console.WriteLine(hashSet.Contains(2));
    }
    
    public ListNode ReverseList(ListNode head) 
    {
        helper(head, out var newHead);
        return newHead;
    }
    
    private ListNode helper(ListNode current, out ListNode newHead) 
    {
        newHead = null;
        
        if (current == null) 
        {
            return null;
        }
        
        var next = helper(current.next, out newHead);

        if (next == null) 
        {
            newHead = current;
        } 
        else 
        {
            next.next = current;
        }
        
        return current;
    }
}

public class ListNode 
{
    public int val;
    public ListNode next;

    public ListNode(int val = 0, ListNode next = null) 
    {
        this.val = val;
        this.next = next;
    }
}

这是我得到的错误:

编译错误(第 13 行,第 30 列):)预期
的编译错误(第 13 行,第 37 列):;预期
的编译错误(第 13 行,第 37 列):无效的表达式术语 ')'

我已经连续花了 2 个小时试图找出问题所在。请帮帮我。

是我的在线代码。

标签: c#syntaxsyntax-errorout

解决方案


我在 dotnet fiddle 尝试了您的示例,似乎编译器(版本)很重要。在 .NET 4.7.2 编译器上运行您的代码时,我遇到了同样的异常,但是当您将编译器更改为 Roslyn 3.8 或 .NET 5 时,示例工作正常。


推荐阅读