How do I convert a decimal to an int in C#?

后端 未结 12 2432
再見小時候
再見小時候 2020-12-02 13:47

How do I convert a decimal to an int?

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 14:35

    I find that the casting operator does not work if you have a boxed decimal (i.e. a decimal value inside an object type). Convert.ToInt32(decimal as object) works fine in this case.

    This situation comes up when retrieving IDENTITY/AUTONUMBER values from the database:

    SqlCommand foo = new SqlCommand("INSERT INTO...; SELECT SCOPE_IDENTITY()", conn);
    int ID = Convert.ToInt32(foo.ExecuteScalar());  // works
    int ID = (int)foo.ExecuteScalar();              // throws InvalidCastException
    

    See 4.3.2 Unboxing conversions

提交回复
热议问题