开发者

should I use Convert class?

For instance, in the following scenario

Convert.I开发者_如何学编程nt64(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.

I would recommend callings long.Parse because it makes the intent (string parsing) clearer.

I recommend using the Convert class if the type that you're converting from might change. (Or if you're converting from object)


Just for completeness to the other answers, don't forget about long.TryParse which is generally safer if you are unsure of the input string format.


Convert.Int64 calls long.Parse internally, just does a null check before. 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 actually calls long.Parse with the CultureInfo.CurrentCulture after first doing a null check on the string. So as long as you know the string is not going to be null, you can save the step and call long.Parse

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜