C# 控制台命令C中的var#

C# 控制台命令C中的var#,c#,C#,如何在控制台命令中插入变量?我的意思是这样的: string color = Console.readline(); Console.ForegroundColor = ConsoleColor.color; 你是说: string color = Console.ReadLine(); Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), color); 你是说: string color = C

如何在控制台命令中插入变量?我的意思是这样的:

string color = Console.readline();
Console.ForegroundColor = ConsoleColor.color;
你是说:

string color = Console.ReadLine();
Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), color);
你是说:

string color = Console.ReadLine();
Console.ForegroundColor = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), color);

您必须将字符串转换为控制台颜色。像这样:

using System;

class Program {
    static void Main(string[] args) {
        var colorName = Console.ReadLine();
        try {
            ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName, true);
            if (color == Console.BackgroundColor) throw new ArgumentException("That would make invisible output");
            Console.ForegroundColor = color;
            Console.WriteLine("Okay");
        }
        catch (ArgumentException ex) {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }
}

这不是最好的解决方案,法国人不会理解为什么“Blanc”不起作用。

您必须将字符串转换为控制台颜色。像这样:

using System;

class Program {
    static void Main(string[] args) {
        var colorName = Console.ReadLine();
        try {
            ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorName, true);
            if (color == Console.BackgroundColor) throw new ArgumentException("That would make invisible output");
            Console.ForegroundColor = color;
            Console.WriteLine("Okay");
        }
        catch (ArgumentException ex) {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }
}
这不是最好的解决方案,法国人不会理解为什么“Blanc”不起作用。

Enum.Parse()在输入值不是枚举的一部分时抛出ArgumentException。FormatException从何而来?如果输入值不是枚举的一部分,则Enum.Parse()会引发ArgumentException。例外从何而来?