C#/.NET: Why can't I cast this decimal to an int? [duplicate]
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 nei开发者_StackOverflow社区ther 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.
Because there is an explicit conversion defined in the framework from decimal to int. Read this MSDN documentation.
精彩评论