如何在 C# 中将颜色作为参数传递?

问题描述 投票:0回答:3

我需要在控制台应用程序中多次更改字体颜色。 而不是每次键入(或复制):

Console.ForegroundColor = ConsoleColor.MyColor;
在我的代码中, 我只想打字
c(Red)
c(Yellow)
。 我想过这样的事情:

static void c(<???> myColor){
   Console.ForegroundColor = ConsoleColor.MyColor;
}

我怎样才能做到这一点?

c# colors console-application
3个回答
2
投票

这里有一个方法可以用来设置控制台的前景色。我将该功能命名为

SetConsoleForeground 
,但您可以随意设置它,例如
c

/// <summary>
/// Sets Console Foreground color to the given color
/// </summary>
/// <param name="consoleColor">Foreground color to set</param>
private static void SetConsoleForeground Color(ConsoleColor consoleColor) {
    Console.ForegroundColor = consoleColor;
}

0
投票

而不是传递

c(Red)
传递
c(ConsoleColor.Red)
并在方法定义中使用
ConsoleColor
枚举类型的参数
c()

public static void c(ConsoleColor myColor){
   Console.ForegroundColor = myColor;
} 

调用函数使用

c(ConsoleColor.Red);

MSDN 控制台颜色


我只想输入 c(Red) 或 c(Yellow)

如果您想传递名为

Red
Yellow
的字符串并将
ForegroundColor
分配给您的控制台,那么您可以尝试以下

public static void SetForegroundColor(string colorName)
{
   //Set black as foreground color if TryParse fails to parse color string. 
   if(Enum.TryParse(ConsoleColor, colorName, out ConsoleColor color)
       Console.ForegroundColor = color;
   else
       Console.ForegroundColor = ConsoleColor.Black;

}

现在你可以将颜色名称作为字符串传递给这个函数,喜欢

SetForegroundColor("Red");
SetForegroundColor("Yello");

MSDN:Enum.TryPrase


0
投票
public  class ConsoleExtension
{
    static Dictionary<char, ConsoleColor> colors = new Dictionary<char, ConsoleColor>
        {
            {'w', ConsoleColor.White },
            {'g', ConsoleColor.Green },
            {'r', ConsoleColor.Red },
            {'b', ConsoleColor.Blue },
            {'y', ConsoleColor.Yellow },
            {'m', ConsoleColor.Magenta }
        };
    public static void CC(char color = 'w')
    {
        try
        {
            Console.ForegroundColor = colors[color];
        }
        catch
        {
            Console.WriteLine("Color isn't correct");
        }
    }
}

现在您可以调用

CC('g')
将 ForeGroundColor 更改为绿色

或者您可以使用这样的代码段:

CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
    <Title>Change textColor and WriteLine</Title>
    <Author>IZ</Author>
    <Shortcut>cwc</Shortcut>
    <Description>Set your text color</Description>
    <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
</Header>
<Snippet>
    <Declarations>
        <Literal>
            <ID>TextColor</ID>
            <Default>Green</Default>
        </Literal>
        <Literal>
            <ID>Text</ID>
            <Default>Text</Default>
        </Literal>
    </Declarations>
    <Code Language="CSharp">
        <![CDATA[Console.ForegroundColor = ConsoleColor.$TextColor$;
        Console.WriteLine("$Text$");]]>
    </Code>
</Snippet>

更好,因为现在您可以在任何地方使用它,而且它更短 - 仅输入“cwc”和 TAB

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Text");
© www.soinside.com 2019 - 2024. All rights reserved.