[英]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);
}
我不知道有什么魔法,盡管你可以搜索包管理器/github。 您將不得不解析輸入字符串。 .Net小提琴。
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()
的靜態方法。 您可以使用此方法查看輸入字符串是否可以解析為每種類型。 如果您處理的類型數量非常有限,這只是一個很好的解決方案。對於未來的讀者......我有類似的任務,我想出了以下解決方案: *任何來自控制台的輸入都被視為字符串類型。在 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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.