C#代码无法编译.null和int之间没有隐式转换

Hca*_*tek 81 c# string null nullable

可能重复:
可空类型和三元运算符:为什么是`?10:null`禁止?

为什么这不起作用?看起来像有效的代码.

  string cert = ddCovCert.SelectedValue;
  int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
  Display(x);
Run Code Online (Sandbox Code Playgroud)

我该怎么编码呢?该方法采用Nullable.如果下拉列表中选择了一个字符串,我需要将其解析为一个int,否则我想将null传递给该方法.

Meh*_*ari 258

int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
Run Code Online (Sandbox Code Playgroud)

  • 我有时需要它,但总是忘记并最终到达这里:D.谢谢 (3认同)
  • 所以很奇怪,您需要强制转换为null。为什么null不能成为通用类型? (3认同)

Sco*_*ski 9

我遇到了同样的事情......我通常只是将null转换为(int?)

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);
Run Code Online (Sandbox Code Playgroud)