我无法理解枚举在 C# 中的工作方式,因为它们打印自己的“名称”而不是它们代表的值。例如,我想使用枚举将工作日翻译成另一种语言。这些代表星期几。
enum Weekdays { Mon = 1, Tue, Wed, Thu, Fri, Sat, Sun };
我下面的方法是有问题的。如果我没有对每个案例进行 (int)-casts,由于类型差异(?),它不会编译。
// Returns weekday in Norwegian.
private static string translateWeekday(int nummer)
{
switch (nummer)
{
case (int)Weekdays.Mon:
return "Mandag";
/* ...... */
case (int)Weekdays.Sun:
return "Søndag";
}
return "Invalid input.";
}
我用这个测试我的程序。我也必须投这个。
static void Main(string[] args)
{
var ukedag = translateWeekday((int)Weekdays.Tue);
Console.WriteLine(ukedag);
}
我现在真正的问题是为什么我需要这些强制转换,为什么 C# 不打印出值,而是打印出每个枚举的名称(如果我尝试打印出它们)?在我的例子中,我应该如何正确地做到这一点(即不必在一个开关中使用 7 次强制转换,这似乎是不必要的)?
最佳答案
简单的改变
private static string translateWeekday(int nummer)
到
private static string translateWeekday(Weekdays nummer)
并移除所有的类型转换。
why doesn't C# print out the values, but the names of each enum if I try to print them out?
枚举是一种具有特殊 ToString
的类型,默认情况下,它“打印”值的名称而不是值。
and (if) there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant
您可以使用 .ToString("d")
打印枚举的“值”。
string str1 = Weekdays.Mon.ToString(); // Mon
string str2 = Weekdays.Mon.ToString("d"); // 1
关于c# - 如何在 C# 中正确切换枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29014054/