Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vb.net - Integer.Parse vs. CInt

Basically, I have been using both Integer.Parse and CInt in most of my daily programming tasks, but I'm a little bit confused of what the difference is between the two.

What is the difference between Integer.Parse and CInt in VB.NET?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CInt does a whole lot more than Integer.Parse.

CInt will first check to see if what it was passed is an integer, and then simply casts it and returns it. If it's a double it will try to convert it without first converting the double to a string.

See this from the help for CInt and other Type Conversion Functions

Fractional Parts. When you convert a nonintegral value to an integral type, the integer conversion functions (CByte, CInt, CLng, CSByte, CShort, CUInt, CULng, and CUShort) remove the fractional part and round the value to the closest integer.

If the fractional part is exactly 0.5, the integer conversion functions round it to the nearest even integer. For example, 0.5 rounds to 0, and 1.5 and 2.5 both round to 2. This is sometimes called banker's rounding, and its purpose is to compensate for a bias that could accumulate when adding many such numbers together.

So in short, it does much more than convert a string to an integer, e.g. applying specific rounding rules to fractions, short circuting unecessary conversions etc.

If what you're doing is converting a string to an integer, use Integer.Parse (or Integer.TryParse), if you're coercing an unknown value (e.g. a variant or object from a database) to an integer, use CInt.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...