1

我正在尝试了解 C# 8.0 开关表达式的工作原理并且有几个问题。

  1. null为什么在默认情况下不能使用value ?编译器抛出Cannot convert null to 'int' because it is a non-nullable value type错误。
  2. 为什么它试图将 null 值转换为int而函数的返回类型是'double?'?

这是我正在玩的功能:

public static double? SwitchFunction(int x) =>
    x switch
    {
        1 => 1,
        _ => null
    };
4

3 回答 3

7

在 switch 表达式中,所有可能的值必须(隐式转换为)相同的类型。因为您的第一种情况是1 => 1,并且您没有将整数文字转换为除 之外的类型int,因此将假定其余情况int也是如此。您需要将该 1 转换(double?)为让编译器将其余情况也解释为double?可空类型 - 这将解决您的两个问题。

于 2019-11-18T22:09:37.583 回答
2

您遇到了条件表达式中经常遇到的问题。

// Compiler Error CS0173
// Type of conditional expression cannot be determined because 
// there is no implicit conversion between 'int' and '<null>'
//
// var d2 = i == 1 ? 1 : null; 

// This works
var d2 = i == 1 ? 1 : (double?) null;

要解决switch表达式中的问题,您可以通过指定 is 的类型来帮助编译器null

int i = 2;
var d = i switch
{
    1 => 1,
    _ => (double?)null
};
于 2019-11-18T22:31:29.737 回答
0

我遇到了同样的问题,导致了不同的错误消息:“没有为 switch 表达式找到最佳类型”。

var isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

在阅读此处的答案之前,我无法理解此错误消息。编译器无法确定 isRequired 的类型应该是什么。我的意图是布尔?将代码更改为此会使错误消息消失:

var isRequired = someIntValue switch
    {
      0 => (bool?)null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

另一方面,我可以告诉编译器我想要什么:

bool? isRequired = someIntValue switch
    {
      0 => null,
      1 => false,
      2 => true,
      _ => throw new NotSupportedException(),
    };

我在 GitHub 上读到他们打算在未来的版本中解决这个问题。

于 2020-02-18T09:30:48.630 回答