[英]Type of input C#
實際上我正在嘗試編寫一個小程序來讀取用戶的輸入,以決定它是否為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");
}
你可以用這個:
string x = Console.ReadLine();
int i;
if(int.TryParse(x, out i))
Console.WriteLine("int");
else
Console.WriteLine("not int");
如果TryParse()
返回true
,則解析的值存儲在i
只需使用Int.TryParse,如本例所示
int result;
string x = Console.ReadLine();
if(int.TryParse(x, out result))
Console.WriteLine("int");
else
Console.WriteLine("not int");
該方法接受輸入字符串和整數變量。 如果字符串可以轉換為整數,則使用轉換后的字符串初始化整數變量,該方法返回true。 否則,該方法返回false,傳遞的整數變量將設置為零。
作為旁注。 Console.ReadLine返回一個字符串
嘗試
static void check()
{ int result
string x = Console.ReadLine();
if(int.TryParse(x, out result)
Console.WriteLine("int");
else
Console.WriteLine("not int");
}
嘗試這個
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()
將始終返回字符串。 所以你可以嘗試Int.TryParse()
來檢查類型。 檢查以下示例
int output;
string x = Console.ReadLine();
if(int.TryParse(x, out output)
Console.WriteLine("int");
else
Console.WriteLine("not int");
希望這可能對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.