C#ReadLine转换问题

本文关键字:问题 转换 C#ReadLine | 更新日期: 2023-09-27 18:25:35

我是C#的新手,正在研究文本格式。我稍微偏离了课程计划,格式化了用户输入的电话号码。尽管程序编译并运行,但在输入某些内容时会崩溃。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Strings
{
   class Program
   {
       static void Main(string[] args)
       {
           int PhoneNumber = Convert.ToInt32(Console.ReadLine());
           string myString = string.Format("Phone Number: {0:(###) ###-####}", PhoneNumber);
           Console.WriteLine(myString);
           Console.ReadLine();
        }
   }
}

C#ReadLine转换问题

代码的问题是intInt32)的最大值为2147483647,这可能小于您输入的电话号码,导致它与OverflowException一起崩溃。

int更改为long:

long PhoneNumber = Convert.ToInt64(Console.ReadLine());
string myString = string.Format("Phone Number: {0:(###) ###-####}", PhoneNumber);
Console.WriteLine(myString);
Console.ReadLine();

但我建议阅读并将电话号码保存在string中,因为整数作为数据类型实际上没有意义。