2016-12-02 35 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(); 
    } 
}