How to convert long to int in .net?

后端 未结 7 2454
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 15:19

I am developing window phone 7 application in silverlight. I am new to the window phone 7 application. I have the long value in String format as follows

String A         


        
7条回答
  •  情深已故
    2021-02-18 16:05

    You have a number stored as a string, and you want to convert it to a numeric type.

    You can't convert it to type int (also known as Int32), because as the other answers have mentioned, that type does not have sufficient range to store your intended value.

    Instead, you need to convert the value to a long (also known as Int64), instead. The simplest and most painless way to do that is using the TryParse method, which converts a string representation of a number to its 64-bit signed integer equivalent.

    The advantage of using this method (instead of something like Parse) is that it does not throw an exception if the conversion fails. Since exceptions are expensive, you should avoid throwing them unless absolutely necessary. Instead, you specify the string containing the number to convert as the first argument to the method, and an out value to receive the converted number if the conversion succeeds. The return value is a Boolean, indicating whether or not the conversion was successful.

    Sample code:

    private void ConvertNumber(string value)
    {
        Int64 number; // receives the converted numeric value, if conversion succeeds
    
        bool result = Int64.TryParse(value, out number);
        if (result)
        {
             // The return value was True, so the conversion was successful
             Console.WriteLine("Converted '{0}' to {1}.", value, number);
        }
        else
        {
            // Make sure the string object is not null, for display purposes
            if (value == null)
            {
                value = String.Empty;
            }
    
             // The return value was False, so the conversion failed
            Console.WriteLine("Attempted conversion of '{0}' failed.", value);
        }
    }
    

提交回复
热议问题