无法将类型'long'隐式转换为"int?"? [英] Cannot implicitly convert type 'long' to "int?"?

查看:903
本文介绍了无法将类型'long'隐式转换为"int?"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

It a very simple question - convert a type long variable to a Nullable int type (int?). (see example below- not the actual code)

int? y = 100;

long x = long.MaxValue;

y = x;

我遇到编译时错误.

无法将类型'long'隐式转换为'int?'.存在显式转换(您是否缺少类型转换?).

"Cannot implicitly convert type 'long' to 'int?'. An explicit conversion exists (are you missing a cast?).

我确实有此解决方案(请参阅解决方案部分下方),我对问题的好奇心是建议使用的3种解决方案中的哪一种?

I do have the fix ( see below the solution section), My curiosity in posting the question is of the 3 solutions which one is recommended?

解决方案

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

提前感谢您的建议

推荐答案

要求进行显式转换的原因是,并非long的所有值都可以表示为int.编译器或多或少说您可以做到这一点,但是您必须告诉我您知道自己在做什么".

The reason you require an explicit conversion is that not all values of long can be represented as an int. The compiler is more or less saying 'you can do this, but you have to tell me you know what you're doing'.

文档,如果不能将long表示为int,则Convert.ToInt32将检查并抛出OverflowException.您可以在参考源中看到实现-只是此检查然后是演员表.

Per 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 - it's just this check and then a cast.

后两个选项(通常)是相同的,尽管unchecked出现溢出也允许进行强制转换是编译器的默认值.如果您将编译器默认设置更改为使用/checked开关 如果不在unchecked块中,则会得到一个OverflowException.

The second two options are (usually) the same and allow the cast despite an overflow as unchecked is the compiler default. If you change the compiler default to checked using the /checked switch then you'll get an OverflowException if not in an unchecked block.

关于哪个是最佳",这取决于您的要求.

As to which is 'best', it depends what your requirement is.

这篇关于无法将类型'long'隐式转换为"int?"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆