What is the difference between Convert.ToInt32 and (int)?

后端 未结 12 1636
星月不相逢
星月不相逢 2020-11-27 03:11

The following code throws an compile-time error like

Cannot convert type \'string\' to \'int\'

string name = Session[\"name1\"].ToString();
int i = (         


        
12条回答
  •  醉酒成梦
    2020-11-27 04:00

    To quote from this Eric Lippert article:

    Cast means two contradictory things: "check to see if this object really is of this type, throw if it is not" and "this object is not of the given type; find me an equivalent value that belongs to the given type".

    So what you were trying to do in 1.) is assert that yes a String is an Int. But that assertion fails since String is not an int.

    The reason 2.) succeeds is because Convert.ToInt32() parses the string and returns an int. It can still fail, for example:

    Convert.ToInt32("Hello");
    

    Would result in an Argument exception.

    To sum up, converting from a String to an Int is a framework concern, not something implicit in the .Net type system.

提交回复
热议问题