.Net Parse versus Convert

后端 未结 5 496
失恋的感觉
失恋的感觉 2020-12-17 16:23

In .Net you can read a string value into another data type using either .parse or Convert.To.

I\'m not fam

相关标签:
5条回答
  • 2020-12-17 17:17

    If you need speed, I'm pretty sure a direct cast is the fastest way. That being said, I normally use .Parse or .TryParse because is seems to make things easier to read, and behave in a more predictable manner.

    Convert actually calls Parse under the hood, I believe. So there is little difference there, and its really just seems to be a matter of personal taste.

    0 讨论(0)
  • 2020-12-17 17:20

    Here's an answer for you:

    http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=77428

    Though I think in modern versions of .NET, the best thing to do is use TryParse in any case, if there's any doubt that the conversion will work.

    0 讨论(0)
  • 2020-12-17 17:21

    There is also the DirectCast method which you should use only if you are sure what the type of the object is. It is faster, but doesn't do any proper checks. I use DirectCast when I'm extracting values from a loosely typed DataTable when I know the type for each column.

    0 讨论(0)
  • 2020-12-17 17:22

    The Convert.ToXXX() methods are for objects that might be of the correct or similar type, while .Parse() and .TryParse() are specifically for strings:

    //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 
    }
    

    If you compile with optimisation flags TryParse is very quick - it's the best way to get a number from a string. However if you have an object that might be an int or might be a string Convert.ToInt32 is quicker.

    0 讨论(0)
  • 2020-12-17 17:27

    I'm a big fan of TryParse, since it saves you a lot of headache of error catching when there's a chance the value you're going to parse is not of the appropriate type.

    My order is usually:

    • Parse (if I can be sure the value will be the right type, and I do try to ensure this)
    • TryParse (if I can't be sure, which happens whenever user input is involved, or input from a system you cannot control)
    • Convert (which I think I have not used since I started using Parse and TryParse, but I could be wrong)
    0 讨论(0)
提交回复
热议问题