Los Convert.ToXXX()
métodos son los objetos que podrían ser del tipo correcto o similares, mientras que .Parse()
y .TryParse()
son específicamente para cadenas:
//o is actually a boxed int
object o = 12345;
//unboxes it
int castVal = (int) 12345;
//o is a boxed enum
object o = MyEnum.ValueA;
//this will get the underlying int of ValueA
int convVal = Convert.ToInt32(o);
//now we have a string
string s = "12345";
//this will throw an exception if s can't be parsed
int parseVal = int.Parse(s);
//alternatively:
int tryVal;
if(int.TryParse(s, out tryVal)) {
//do something with tryVal
}
Si se compila con parámetros de optimización TryParse es muy rápida - que es la mejor forma de obtener un número de una cadena. Sin embargo, si tiene un objeto que podría ser un int o podría ser una cadena Convert.ToInt32 es más rápido.