C# 如何确定字符串是否为数字类型

在本文中,我们将讨论如何使用 C# 中的 TryParse() 方法来确定 String 是否表示数字类型。
这个方法需要两个参数。 第一个参数是我们要转换的值,第二个参数是布尔值将存储其中的输出变量。 此方法返回布尔值。

示例代码

using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;

namespace ConsoleApplication17

{
  class Program
  {
      static void Main(string[] args)

      {
          string numberstr = "1287543";
          long n1 = 0;
          bool canConvert = long.TryParse(numberstr, out n1);

          if (canConvert)
              Console.WriteLine("number1 = {0}", n1);
          else
              Console.WriteLine("numberstring is not a valid long");

          byte n2 = 0;
          numberstr = "255";
          canConvert = byte.TryParse(numberstr, out n2);

          if (canConvert)
              Console.WriteLine("number2 = {0}", n2);
          else
              Console.WriteLine("numberstring is not a valid byte");

          decimal n3 = 0;
          numberstr = "27.3";
          canConvert = decimal.TryParse(numberstr, out n3);

          if (canConvert)
              Console.WriteLine("number3 = {0}", n3);
          else
              Console.WriteLine("numberstring is not a valid decimal");

          System.Console.ReadLine();

      }
  }

}
日期:2020-04-11 22:50:33 来源:oir作者:oir