2016-12-02 33 views
1

我想做一個函數,在調用時改變控制檯的顏色,以及我選擇的那些顏色。我不想每次都寫3條指令,所以這就是爲什麼我希望它在函數中。如何使用變量完成指令?

到目前爲止,我已經做了一些與此類似:

public static void WindowColor(string Background, string Foreground) 
{ 
    Console.BackgroundColor = ConsoleColor.Background; 
    Console.ForegroundColor = ConsoleColor.Foreground; 
    Console.Clear(); 
} 

static void Main(string[] args) 
{ 
    WindowColor("DarkCyan","White"); 
} 

其中ConsoleColor.BackgroundConsoleColor.Foreground我想與ConsoleColor.DarkCyanConsoleColor.White被替換,因爲我在WindowColor("DarkCyan","White");調用。

但我得到這個錯誤:

'ConsoleColor' does not contain a definition for 'Background'.

現在我得到的BackgroundConsoleColor.Background不被視爲一個變量,而是作爲指令的一部分的事實,但問題是:我怎麼能使BackgroundForeground被視爲以變量的形式完成指令?

+4

爲什麼不使用'WindowColor(ConsoleColor.DarkCyan,ConsoleColor.White)'而不是?或者在C#6和'WindowColor(DarkCyan,White)'中使用'static''? (並將每個參數的類型更改爲「ConsoleColor」,理想情況下將其重命名爲慣用語言。)您是否希望*刪除編譯時檢查? –

+0

我不知道我能做到這一點,我剛開始使用C#。但它解決了我的問題。謝謝。 – BatchGuy

回答

4

通常情況下,你只需使用正確類型的參數,而不是字符串:

public static void WindowColor(ConsoleColor background, ConsoleColor foreground) 
{ 
    Console.BackgroundColor = background; 
    Console.ForegroundColor = foreground; 
    Console.Clear(); 
} 

static void Main(string[] args) 
{ 
    WindowColor(ConsoleColor.DarkCyan, ConsoleColor.White); 
} 

如果你堅持有字符串作爲參數,你將不得不對其進行解析:

public static void WindowColor(string Background, string Foreground) 
{ 
    Console.BackgroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), Background, true); 
    Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), Foreground, true); 
    Console.Clear(); 
} 

static void Main(string[] args) 
{ 
    WindowColor("DarkCyan","White"); 
} 
+0

我剛剛發現我可以做到這一點。謝謝您的回答! – BatchGuy

+0

只是使用'Parse'是很危險的。如果字符串不能被解析,這會引發錯誤。 – Abion47

1

Console.ForegroundColorConsole.BackgroundColor的類型是ConsoleColor,而不是字符串。如果你希望你的函數來工作,你將需要更改參數類型ConsoleColor:

public static void WindowColor(ConsoleColor Background, ConsoleColor Foreground) 
{ 
    Console.BackgroundColor = Background; 
    Console.ForegroundColor = Foreground; 
    Console.Clear(); 
} 

或者,你可以把它作爲一個字符串,然後嘗試解析字符串作爲枚舉值:

public static void WindowColor(string Background, string Foreground) 
{ 
    ConsoleColor b, f; 

    if ( Enum.TryParse(Background, out b) 
     && Enum.TryParse(Foreground, out f)) 
    { 
     Console.BackgroundColor = b; 
     Console.ForegroundColor = f; 
     Console.Clear(); 
    } 
}