从Console.ReadLine输入中检索数据类型

我对编程很新,我有挑战,但我需要你的帮助。 我的任务是编写一个从控制台读取内容的程序,然后如果它的编号将打印1,如果它的字符串看起来像这样(字符串+ *)。 inheritance我的代码,但有一些错误,我无法弄明白。这是必须使用Switch – Case。

static void Main(string[] args) { string x = Console.ReadLine(); switch (x) { case "int" : int i = int.Parse(x); i = i + 1; Console.WriteLine(i); break; case "double": double d = double.Parse(x); d = d + 1; Console.WriteLine(d); break; case "string": string s = (x); Console.WriteLine(s + "*"); break; default: break; } } 

switch case不能那样工作。 它接受您传递的参数的数据类型:

 string x = Console.ReadLine(); switch(x) //x is the argument for switch 

原样。 在你的情况下, x始终是一个string 。 Switch检查参数的并找到该值的设计case ,它检查参数的类型并找到该值的设计case

但是,如果您的目标是检查string是否可以转换intdoubleDateTime ,其他一些数据类型,或者只能读取为string ,则应使用TryParse为单个数据类型执行此操作:

 int myInt; double myDouble; bool r1 = int.TryParse(x, out myInt); //r1 is true if x can be parsed to int bool r2 = double.TryParse(x, out myDouble); //r2 is true if x can be parsed to double 

编辑:

由于必须使用switch case,因此可以将结果放在一个整数中:

 int a = (r1 ? 1 << 1 : 0) + (r2 ? 1 : 0); //0 if string, 1 if int, 2 if double, 3 if int or double 

使用bit-flag概念,并使switch案例如下:

 switch (a){ case 0: //string case Console.WriteLine(x + "*"); break; case 1: //int case Console.WriteLine((Convert.ToInt32(x) + 1).ToString()); break; case 2: //double case Console.WriteLine((Convert.ToDouble(x) + 1).ToString()); break; case 3: //int or double case Console.WriteLine((Convert.ToInt32(x) + 1).ToString()); break; } 

原版的:

然后你可以做这样的事情:

 if (r1){ //parsable to int //do something, like raise the number by 1 myInt += 1; x = myInt.ToString(); } else if (r2){ //parsable to double //do something, like raise the number by 1 myDouble += 1; x = myDouble.ToString(); } else { //cannot be parsed to any //do something like add `*` x = x + "*"; } Console.WriteLine(x); 

希望这会工作,现在它可以使用int,double,string我们可以扩展

  public static class Extenstions { public static bool IsValid(this string source) where T : struct { MethodInfo tryParse = (MethodInfo)typeof(T).GetMember("TryParse").FirstOrDefault(); if (tryParse == null) return false; return (bool)tryParse.Invoke(null, new object[] { source, null }); } public static Type GetParsableType(this string source) { return source.IsValid()&&!source.Contains(".") ? typeof(int) : source.IsValid() ? typeof(double) : typeof(string); } } class Program { static void Main(string[] args) { while (true) { string x = Console.ReadLine(); switch (x.GetParsableType().Name.ToLower()) { case "int32": case "int": int i = int.Parse(x); i = i + 1; Console.WriteLine(i); break; case "double": double d = double.Parse(x); d = d + 1; Console.WriteLine(d); break; case "string": string s = (x); Console.WriteLine(s + "*"); break; default: ; break; } } } }