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 个小时试图找出问题所在。请帮帮我。
Here 是我的在线代码。
答案 0 :(得分:4)
我在 dotnet fiddle 尝试了您的示例,似乎编译器(版本)很重要。在 .NET 4.7.2 编译器上运行您的代码时,我遇到了同样的异常,但是当您将编译器更改为 Roslyn 3.8 或 .NET 5 时,示例可以正常工作。
答案 1 :(得分:1)
更改第 13 行
helper(head, out var newHead);
到
var newHead = new ListNode();
helper(head, out newHead);