如何知道用户在C#中输入了什么

How to know what user entered in C#

例如:

cw("enter anything");

//我们不知道用户是否输入了 int 或 string 或任何其他数据类型,因此我们将检查为,

if(userEntered == int){}
if(userEntered==string){}

换句话说:如果用户输入例如int值,我们转换并保存,但如果我们不知道用户输入的是什么,我们将如何判断或检测?

对于接受用户输入的控制台应用程序,假设它是一个字符串开头,因为字符串将能够容纳任何输入。

如果需要,您可以将其解析为其他数据类型,例如整数或浮点数。

对此没有严格的规定,用户只需输入一个字符串值。它可以是 null 或空字符串或任何其他字符串,它们可能会或可能不会转换为 int 或 decimal 或 DateTime 或任何其他数据类型。所以你只需要解析输入数据并检查它是否可以转换为数据类型。

 Console.WriteLine("enter someting");
 string read = Console.ReadLine();

Console.Readline() read user input and will return a string

From here try to convert/parse it to other data type.

您可以通过 console.readline 要检查它是字符串还是整数,你可以这样做 默认用户输入是字符串 检查以下代码片段

class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string input = Console.ReadLine();
            Console.WriteLine(input);

            int num2;
            if (int.TryParse(input, out num2))
            {
                Console.WriteLine(num2);
            }
        }
}

这是一个检查用户输入的是整数还是字符串值的示例:

Console.WriteLine("Enter value:");
string stringValue = Console.ReadLine();

int intValue;
if(int.TryParse(stringValue, out intValue))
{
    // this is int! use intValue variable
}
else
{
    // this is string! use stringValue variable
}

输入字符串后,您可以使用 TryParse 查看它是整数还是小数(除其他外)...

string userEntered = Console.ReadLine();
int tempInt;
decimal tempDec;

if(int.TryParse(userEntered, out tempInt))
  MessageBox.Show("You entered an int: " + tempInt);
else if(decimal.TryParse(userEntered, out tempDec))
 MessageBox.Show("You entered a decimal: " + tempDec);
else MessageBox.Show("You entered a string: " + userEntered);
public class MainClass
{
public static void Main(string[] args)
{
    String value = Console.ReadLine();
    var a = new MainClass();
    if a.IsNumeric(value){
    //your logic with numeric
    }
    else 
    {
    //your logic with string
    }
}

public Boolean IsNumeric(String value){
 try 
   var numericValue = Int64.Parse(value);
   return true;
 catch 
   return false;
}

在这种情况下,有一个单独的函数,它会尝试将其转换为数字,如果成功 return 为真,否则为假。有了这个,您将避免进一步的代码重复来检查您的值是否为数字。