简体   繁体   English

输入类型C#

[英]Type of input C#

Actually I'm trying to write small program that read input from user to decide whether is it integer or not. 实际上我正在尝试编写一个小程序来读取用户的输入,以决定它是否为integer

object x=Console.ReadLine();
check(x);

static void  check(object x)
{   
     if (x.GetType() == typeof(int))
      Console.WriteLine("int");
     else
      Console.WriteLine("not int");   

}

You can use this: 你可以用这个:

string x = Console.ReadLine();

int i;

if(int.TryParse(x, out i))
     Console.WriteLine("int");
 else
     Console.WriteLine("not int");   

If the TryParse() returns true , the parsed value is stored in i 如果TryParse()返回true ,则解析的值存储在i

Just use Int.TryParse as in this example 只需使用Int.TryParse,如本例所示

int result;
string x = Console.ReadLine();
if(int.TryParse(x, out result))
  Console.WriteLine("int");
else
  Console.WriteLine("not int");   

The method accepts the input string and an integer variable. 该方法接受输入字符串和整数变量。 If the string can be converted to an integer number, then the integer variable is initialized with the converted string and the method returns true. 如果字符串可以转换为整数,则使用转换后的字符串初始化整数变量,该方法返回true。 Otherwise the method returns false and the integer variable passed will be set to zero. 否则,该方法返回false,传递的整数变量将设置为零。

As a side note. 作为旁注。 Console.ReadLine returns a string Console.ReadLine返回一个字符串

try 尝试

static void  check()
{   int result
    string x = Console.ReadLine();
    if(int.TryParse(x, out result)
      Console.WriteLine("int");
    else
      Console.WriteLine("not int");   

}

Try this 尝试这个

int isInteger;
Console.WriteLine("Input Characters: ");
string x = Console.ReadLine();
if(int.TryParse(x, out isInteger)
  Console.WriteLine("int");
else
  Console.WriteLine("not int"); 

Console.ReadLine() Will Always Return String . Console.ReadLine()将始终返回字符串。 So you can Try Int.TryParse() To Check the type. 所以你可以尝试Int.TryParse()来检查类型。 Check the bellow Example 检查以下示例

   int output;
   string x = Console.ReadLine();
   if(int.TryParse(x, out output)
       Console.WriteLine("int");
   else
      Console.WriteLine("not int"); 

hope This may helpful for you. 希望这可能对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM