簡體   English   中英

在控制台應用程序 C# 中檢查輸入數據類型

[英]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()的靜態方法。 您可以使用此方法查看輸入字符串是否可以解析為每種類型。 如果您處理的類型數量非常有限,這只是一個很好的解決方案。
  • 您可以使用解析表達式語法(“PEG”)或類似方法,它允許您定義用於解析任意文本的正式語法。 這種方法的優點是您還可以支持復雜的結構(即值列表、嵌套值等)。 這種方法非常靈活和富有表現力,但它也有一個更大的學習曲線。
  • 您可以使用正則表達式,它提供與 PEG 類似的功能,但通常在更有限的上下文中使用。 您應該能夠輕松找到常見簡單數據類型(數字、布爾值、字符串等)的正則表達式。

對於未來的讀者......我有類似的任務,我想出了以下解決方案: *任何來自控制台的輸入都被視為字符串類型。在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM