无法将类型 'long' 隐式转换为 "int?"?

Cannot implicitly convert type 'long' to "int?"?

这是一个非常简单的问题 - 将类型 long 变量转换为 Nullable int 类型 (int?)。 (请参阅下面的示例 - 不是实际代码)

int? y = 100;

long x = long.MaxValue;

y = x;

我遇到编译时错误。

“无法将类型 'long' 隐式转换为 'int?'。存在显式转换(是否缺少强制转换?)。

我确实有解决方案(请参阅下面的解决方案部分),我对发布问题的好奇心是 3 种推荐的解决方案?

解决方案

  y = Convert.ToInt32(x);
  y = (int)x;
  y = unchecked((int) x);  

提前感谢您的建议

您需要 显式 转换的原因是并非 long 的所有值都可以表示为 int。编译器或多或少会说“你 可以 这样做,但你必须告诉我你知道你在做什么”。

根据 the docs, Convert.ToInt32 will check for and throw an OverflowException if the long cannot be represented as an int. You can see the implementation in the reference source - 只是这次检查,然后是强制转换。

后两个选项(通常)是相同的,并且尽管溢出也允许强制转换为 unchecked is the compiler default. If you change the compiler default to checked using the /checked switch 如果不在 [=] 中,您将得到一个 OverflowException 16=]块。

至于哪个是'best',就看你的要求了。

int是32位整数,而long是64位整数。

long 可以 store/represent 所有 int 值,但所有 long 值不能用 int 表示,所以 longint 这就是为什么 int 可以被编译器隐式转换为 long 而不是相反的原因。

所以这就是我们需要显式 cast/convert longint 的原因,如果 long 不能表示为 int,这可能会导致信息丢失]