C#/.NET : Why can't I cast this decimal to an int?

标签 c# casting decimal int

<分区>

Possible Duplicate:
Why can't I unbox an int as a decimal?

好的,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();
}

我可以将 decimal 转换为 int,只要我转换的是显式声明的 decimal 类型,但是当 decimal 存储在对象类型中时,我不能将 decimal 转换为 int 吗?这是怎么回事?

注意:我知道我可能可以使用 Convert.ToInt32(),但我想弄清楚这个在这里不起作用。

最佳答案

因为框架中定义了从十进制到整数的显式转换。阅读此 MSDN documentation .

关于C#/.NET : Why can't I cast this decimal to an int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307109/

相关文章:

javascript - 如何将非常大的十进制数转换为字符串?

c# - 在 ObservableCollection 上实现 AddRange 并适当支持 DataBinding

c# - 复杂的 LINQ 查询

c++ - 查找指向 NULL 的指针

c - 有什么简单的方法可以在c语言中将int类型转换为enum类型?

C# Decimal.Parse 逗号问题

c# - 从字符串中删除垃圾值

java - IntelliJ IDEA 的 Visual Studio 白色背景主题

c++ - 我如何使用 istream_iterator 将 unsigned char vector 转换为字符串?

c# - 如何修剪小数?