简体   繁体   English

我应该使用Convert类吗?

[英]should I use Convert class?

For instance, in the following scenario 例如,在以下情况下

Convert.Int64(string somstring)

or 要么

long.Parse(string somstring);

appear to be doing same kind of work. 似乎在做同样的工作。 Which one is a better practice ? 哪个是更好的做法?

Thanks 谢谢

If you look at the source, Convert.ToInt64(string) simply calls long.Parse , but checks that the string isn't null first. 如果您查看源代码, Convert.ToInt64(string)只是调用long.Parse ,但首先检查字符串是否不为null

I would recommend callings long.Parse because it makes the intent (string parsing) clearer. 我建议调用long.Parse因为它可以使意图(字符串解析)更加清晰。

I recommend using the Convert class if the type that you're converting from might change. 我建议使用Convert类,如果类型你是可能会发生变化转换。 (Or if you're converting from object ) (或者,如果您是从object转换的)

只是为了确保其他答案的完整性,请不要忘记使用long.TryParse ,如果不确定输入字符串的格式,通常这会更安全。

Convert.Int64 calls long.Parse internally, just does a null check before. Convert.Int64调用long.Parse内部,之前只是做一个空检查。 Here's the guts: 这是胆量:

if (value == null)
{
    return 0L;
}
return long.Parse(value, CultureInfo.CurrentCulture);

If you need the null check, Convert.Int64 is safer that's all, otherwise no difference. 如果需要空检查,那么Convert.Int64更安全,否则没有区别。

Convert.Int64 actually calls long.Parse with the CultureInfo.CurrentCulture after first doing a null check on the string. 在首先对字符串进行空检查之后,Convert.Int64实际上使用CultureInfo.CurrentCulture调用long.Parse。 So as long as you know the string is not going to be null, you can save the step and call long.Parse 因此,只要您知道字符串不会为空,就可以保存该步骤并调用long.Parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM