90

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

为什么这不起作用?似乎是有效的代码。

  string cert = ddCovCert.SelectedValue;
  int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
  Display(x);

我应该如何编码?该方法采用 Nullable。如果下拉选择了一个字符串,我需要将其解析为一个 int 否则我想将 null 传递给该方法。

4

2 回答 2

285
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
于 2009-08-14T17:18:52.550 回答
10

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

int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);
于 2009-08-14T17:19:17.120 回答