在控制台应用程序 C# 中检查输入数据类型

Check Input Data Type In Console Application C#

如何在 C# 控制台应用程序中检查输入数据类型..

Class A
{

 object o=Console.ReadLine();
 //logic here to check data type and print
//e.g type of Integer, Decimal, String etc

}

如果我输入 23 那么它会打印 'Integer'

如果我输入 23.9 那么它会打印 'Decimal'

如果我输入 "abcd" 那么它会打印 'String'

我想做的是.. 像

Class A
{
Type t=Typeof(Console.ReadLine().GetType);
Console.WriteLine(t.Name);
}

我不知道有什么魔法,不过你可以搜索包 managers/github。您将不得不解析输入字符串。 .Net Fiddle.

string o = Console.ReadLine();

string finalType = "String";
if (!string.IsNullOrEmpty(o)){

  // Check integer before Decimal
  int tryInt;
  decimal tryDec;
  if (Int32.TryParse(o, out tryInt)){
    finalType = "Integer";
  }
  else if (Decimal.TryParse(o, out tryDec)){
    finalType = "Decimal";
  }    

}

Console.WriteLine(finalType);

您应该首先检查输入的字符串是否包含在双引号中。如果是这样,打印字符串。

然后使用long.TryParse检查是否可以解析为long。如果是这样,打印整数。

然后用decimal.TryParse看能不能解析成十进制。如果是,打印 Decimal.

你是这个意思吗?

您将需要解析传入的数据。根据您需要处理的类型数量,您可以选择几种不同的路线:

  • 许多简单的数据类型都有一个名为 TryParse() 的静态方法。您可以使用此方法查看是否可以将输入字符串解析为每种类型。如果您处理的类型数量非常有限,这只是一个很好的解决方案。
  • 您可以使用解析表达式语法 ("PEG") 或类似的方法,它允许您定义用于解析任意文本的形式语法。这种方法的优点是您还可以支持复杂的结构(即值列表、嵌套值等)。这种方法非常灵活和富有表现力,但它也有更大的学习曲线。
  • 您可以使用正则表达式,它提供与 PEG 类似的功能,但通常在更有限的上下文中使用。您应该能够轻松找到常见简单数据类型(数字、布尔值、字符串等)的正则表达式。

对于未来的读者......我有类似的任务,我想出了以下解决方案: * 来自控制台的任何输入都被视为字符串 type.In C# 您需要尽可能将输入解析为特定类型。

    var input = Console.ReadLine();

// `typeToCheck`.TryParse(input, out _) - Will return True if parsing is possible.            

                if (Int32.TryParse(input, out _))
                {
                    Console.WriteLine($"{input} is integer type");
                }
                else if (double.TryParse(input, out _))
                {
                    Console.WriteLine($"{input} is floating point type");
                }
                else if (bool.TryParse(input, out _))
                {
                    Console.WriteLine($"{input} is boolean type");
                }
                else if (char.TryParse(input, out _))
                {
                    Console.WriteLine($"{input} is character type");
                }
                else // since you cannot parse to string ... if the previous statements came up false -> IT's STRING Type.
                {
                    Console.WriteLine($"{input} is string type");
                }