2017-01-12 22 views
0

我有問題陣列在C#無法獲得C#陣列工作

裏面我上課的時候我在

>>> public static void Main(string[] args) { 
    Console.WriteLine (new string[] { "I", "Like", "π" }); 
} 

鍵入console說

System.String[] 

相反的陣列我通過。

我想要做的是適合一個數組到一個像這樣的方法:

>>> public static void Main(string[] args) { 
    DoSomething ({ "I", "Like", "π" }); 
} 

>>> public static int DoSomething(string[] array) { 
    for (int i = 0; i > array.Length; i++) { 
     Console.WriteLine (array [i]); 
    } 
} 

我得到一個錯誤說

Unexpected symbol '{' on 'DoSomething ({ "I", "Like", "π" });' 

如何解決這些錯誤?

+0

因爲你不能打印'字符串[]'(這是字符串數組)元素一樣,直接說。 – Prajwal

+2

而你的方法不返回一個int,使該方法無效! –

+0

string []與System.String []是一樣的。 「string」只是「String」的別名 –

回答

2

這就是你的程序應該如何。

public static void Main(string[] args) 
{ 
    DoSomething (new string[] { "I", "Like", "π" }); 
} 

public static void DoSomething(string[] array) 
{ 
    for (int i = 0; i < array.Length; i++) 
    { 
     Console.WriteLine (array [i]); 
    } 
} 

看完你的問題並將它與上面的問題進行比較後,這些是我找到的錯誤。

  1. 您不能直接打印這樣的數組元素。它應該在每個元素的循環中。你不能像這樣創建文字數組。你將不得不指定它是一個特定數據類型的新數組。

  2. 您的方法正在返回int,它不在代碼中,也未在任何地方使用。在這種情況下,你應該使用void

0
public static void Main(string[] args) { 
    DoSomething (new[] { "I", "Like", "π" }); 
} 

public static void DoSomething(string[] array) { 
    for (int i = 0; i < array.Length; i++) { 
     Console.WriteLine (array [i]); 
    } 
} 
+0

您錯過了退貨類型,我正確嗎? – IsuruAb

0

爲了您的第一選擇,我想提出這樣的:

Console.WriteLine("{0} {1} {2}", new string[] { "I", "Like", "π" }); 

或者這樣:

Console.WriteLine(String.Join(" ", new string[] { "I", "Like", "π" })); 

對於第二個是你必須這樣調用方法:

DoSomething (new[] { "I", "Like", "π" }); 

而你需要改變循環以及像follwong:

for (int i = 0; i < array.Length; i++) 
{ 
    Console.WriteLine (array [i]); 
} 
1

既可以使用for循環打印每個數組中的元素,或者使用的string.join在一個單一的statment打印爲如下所示。 \ n您可以使用任何其他分隔符。例如,如果你需要打印逗號分隔的,可以使用(「」陣列)

public static void Main(string[] args) { 
    DoSomething ({ "I", "Like", "π" }); 
} 

public static void DoSomething(string[] array) {   
     Console.WriteLine (string.Join("\n", array); 
}