2017-09-16 76 views
0
object[] RA= {"Ram",123,122}; 
for(int i = 0;i< RA.Length;i++) 
{ 
    if(RA[i].GetType().toSting()=="System.String") 
    { 
     print('string'); 
    } 
    else 
    { 
     print('int'); 
    } 
} 

輸出:如何檢查數據類型和格式同比較

string 
int 
int 

我可以用GetType(),我都試過,但它表明,我可以比較的錯誤。這個問題如何解決?

+0

問題不清楚。你想知道'x'是否可以是一個整數?你想檢查x的字符來檢查它們是否是數字(因爲循環)? –

+0

@GiladGreen先生..我如何更新代碼請看看... –

+0

@mjwills先生這段代碼顯示錯誤。我不能比較這兩個值..我想當有人在對象數組中輸入字符串或整數然後它將打印它是否是int或字符串 –

回答

1

因爲這個問題是問在C#的標籤,所以我對於C# 這個回答讓你期待

輸出
object[] RA= {"Ram",123,122}; 
for(int i = 0;i< RA.Length;i++) 
{ 
    if(RA[i].GetType() == typeof(string)) 
    { 
    Console.WriteLine("string"); 
    } 
    else 
    { 
    Console.WriteLine("int"); 
    } 
} 
+1

原因沒有*編譯*是因爲'toSting'不是'ToString' - - 也許值得一提 – pinkfloydx33

+0

是的你是對的#pinkfloydx33我現在才意識到它的可用性,但由於他的拼寫錯誤,它不是工作 –

2

我想辦法給它有點不同:

  • 正如你想迭代集合和索引的項目並不重要,我會使用foreach loop
  • 與其說GetType使用typeof我會使用is operator的:

一起:

object[] RA = { "Ram", 123, 122 }; 
foreach(var item in RA) 
{ 
    if (item is string) 
    { 
     Console.WriteLine("string"); 
    } 
    else 
    { 
     Console.WriteLine("int"); 
    } 
} 

另外,把它一步我想補充一個使用ternary operator的:

object[] RA = { "Ram", 123, 122 }; 
foreach(var item in RA) 
{ 
    Console.WriteLine(item is string ? "string" : "int"); 
} 

請注意,如果你想要的類型名稱(而不是全名),只需使用:

Console.WriteLine(item.GetType().Name); 
+0

謝謝先生... –

+0

@TechnoSuggest - 不客氣 –

0

如果你也想在自己的原生類型,你可以從數組中的值,如C#7,使用模式匹配:

object[] RA = { "Ram", 123, 122 }; 
for (int i = 0; i < RA.Length; i++) { 
    var r = RA[i]; 
    if (r is string s) { 
    Console.WriteLine($"{i}: string \"{s}\""); 
    } else if (r is int x) { 
    Console.WriteLine($"{i}: int {x}"); 
    } else { 
    Console.WriteLine($"{i}: {r.GetType().Name}"); 
    } 
} 
0

當您使用的Visual Studio 2017年C#7.0你終於能夠在類型使用switch

What's New in C# 7.0 - switch語句有圖案

switch(shape) 
{ 
    case Circle c: 
     WriteLine($"circle with radius {c.Radius}"); 
     break; 
    case Rectangle s when (s.Length == s.Height): 
     WriteLine($"{s.Length} x {s.Height} square"); 
     break; 
    case Rectangle r: 
     WriteLine($"{r.Length} x {r.Height} rectangle"); 
     break; 
    default: 
     WriteLine("<unknown shape>"); 
     break; 
    case null: 
     throw new ArgumentNullException(nameof(shape)); 
} 

應用到你的代碼:

object[] RA= {"Ram",123,122}; 
for(int idx = 0; idx < RA.Length; idx++) 
{ 
    switch(RA[idx]) 
    { 
     case string s: 
      Console.WriteLine($"The type of {s} is string"); 
      break; 
     case int i: 
      Console.WriteLine($"The type of {i} is int"); 
      break; 
     default: 
      Console.WriteLine($"The type of {RA[idx]} is {RA[idx].GetType().Name}"); 
      break; 
    } 
}