C#/.NET:为什么我不能将此小数转换为 int?
可能的重复:
为什么我不能将 int 拆箱为小数?
好吧,C#/.NET 专家,有人能告诉我为什么这个转换有效吗:
static void Main(string[] args)
{
int _int = 0;
decimal _decimal = 1;
_int = (int)_decimal;
Console.ReadLine();
}
...但是这两个都不起作用?
static void Main(string[] args)
{
int _int = 0;
decimal d = 1;
object _decimal = d;
_int = (int)_decimal;
Console.ReadLine();
}
static void Main(string[] args)
{
int _int = 0;
object _decimal = 1M;
_int = (int)_decimal;
Console.ReadLine();
}
只要我所转换的是显式声明的十进制类型,我就可以将小数转换为 int,但是当小数存储在对象类型中时,我无法将小数转换为 int 吗?这是怎么回事?
注意:我知道我可能可以使用 Convert.ToInt32(),但我试图弄清楚这在这里不起作用。
Possible Duplicate:
Why can't I unbox an int as a decimal?
Okay, C#/.NET gurus, can someone tell me why this cast works:
static void Main(string[] args)
{
int _int = 0;
decimal _decimal = 1;
_int = (int)_decimal;
Console.ReadLine();
}
...but neither of these do?
static void Main(string[] args)
{
int _int = 0;
decimal d = 1;
object _decimal = d;
_int = (int)_decimal;
Console.ReadLine();
}
static void Main(string[] args)
{
int _int = 0;
object _decimal = 1M;
_int = (int)_decimal;
Console.ReadLine();
}
I can cast a decimal to an int so long as what I am casting from is an explicitly-declared decimal type, but I can't cast a decimal to an int when the decimal is stored in an object type? What's up with that?
NOTE: I know I can probably use Convert.ToInt32(), but I am trying to figure out this this here is not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为框架中定义了从decimal到int的显式转换。请阅读此 MSDN 文档。
Because there is an explicit conversion defined in the framework from decimal to int. Read this MSDN documentation.