在C#convert.toint32之间(INT)和差 [英] difference between (int) and convert.toint32 in c#

查看:955
本文介绍了在C#convert.toint32之间(INT)和差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我转换目的是通过

 为int(int)的对象

那么当对象的值是0,那么,他给我的错误具体投无效。



当我转换目的是通过



到int

  convert.toint32(对象)

那么他的作品,并给我0表示投是有效的。



和我想知道这就是两者之间的区别。

  1。 (INT)对象
2.convert.toint32(对象)


解决方案

有很多方法可以转换为int,在很大程度上取决于你的来源是什么。



要记住的最重要的事情是错误检查,与(INT),用Convert.ToInt32没有转换的方法愚弄自己证明等,你需要决定要如何接近他们。



铸造( ),与int.Parse解析()都可以产生异常,如InvalidCastException的,FormatException和OverflowException异常,应该使用try / catch来处理失败的结果。



与诠释解析。的TryParse()将返回一个真/假结果,如果解析成功,如果成功将值设置为函数调用给出的输出参数。



如果你是真正试图把任何物体,并把它变成一个int,你是Convert.ToInt32如可能是最好的:

 公共无效TestFunction(对象输入)
尝试{
int值= Convert.ToInt32(输入);
SomeOtherFunction(值);
}
赶上(例外前){
Console.WriteLine(无法确定整数值);
}
}



另一种可能性是依托产生可用在物体上在的ToString()如值:

 公共无效TestFunction(对象输入)
尝试{
int值= int.Parse(input.ToString());
SomeOtherFunction(值);
}
赶上(例外前){
Console.WriteLine(无法确定整数值);
}
}


when i convert a object to int by

(int)object

then when the object value is 0 then he give me error that specific cast not valid.

when i convert a object to int by

convert.toint32(object)

then he works and give me 0 means cast is valid.

and i want to know that what is difference between both.

1. (int)object
2.convert.toint32(object)

解决方案

There are many ways to convert to an int, a lot depends on what your source is.

The biggest thing to keep in mind is error checking, none of the methods are fool proof on their own and so you need to decide how you want to approach them.

Casting with (int), Converting with Convert.ToInt32(), Parsing with int.Parse() all can generate exceptions such as InvalidCastException, FormatException and OverflowException and should use try/catch to handle failed result.

Parsing with int.TryParse() will return a true/false result of if the parsing was successful and if successful set the value to the out parameter given in the function call.

If you are truly trying to take any object and turn it into an int, you are probably best with Convert.ToInt32 such as:

public void TestFunction(object input)
  try {
    int value = Convert.ToInt32(input);
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}

Another possibility would be relying on the object producing a usable value in .ToString() such as:

public void TestFunction(object input)
  try {
    int value = int.Parse(input.ToString());
    SomeOtherFunction(value);
  }
  catch (Exception ex) {
    Console.WriteLine("Could not determine integer value");
  }
}

这篇关于在C#convert.toint32之间(INT)和差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆