gpt4 book ai didi

c# - 从枚举中打印工作日

转载 作者:行者123 更新时间:2023-11-30 15:20:21 25 4
gpt4 key购买 nike

作为编程新手,我的问题可能看起来有点基础,我想要的是使用循环或其他方式打印枚举中提到的所有日期。我已经使用了一个控制台应用程序。非常感谢有关提高 C# 语言编码能力基础知识的提示以及答案。

using System;

namespace _28_11_2016_enum
{
class Program
{
static void Main(string[] args)
{
weekdays wd = weekdays.mon;

for (int i = 0; i < 7; i++)
{


int a = (int)wd;
a = a + i;
wd = (wd)a;// faulty code.
Console.WriteLine(wd);
}
Console.Read();
}
enum weekdays : int
{
mon, tue, wed, thur, fri, sat, sun
}
}

最佳答案

您不必循环 - Enum.GetNames 返回名称,然后 string.Join 将它们连接成一个 string :

 // mon, tue, wed, thur, fri, sat, sun
Console.Write(string.Join(", ", Enum.GetNames(typeof(weekdays))));

如果你想要 int 值:

 // 0, 1, 2, 3, 4, 5, 6
Console.Write(string.Join(", ", Enum.GetValues(typeof(weekdays)).Cast<int>()));

编辑:如果你坚持循环我建议foreach一个:

 // mon == 0 ... sun == 6
foreach (var item in Enum.GetValues(typeof(weekdays))) {
Console.WriteLine($"{item} == {(int) item}");
}

for 循环的情况下

 // do not use magic numbers - 0..7 but actual values weekdays.mon..weekdays.sun 
for (weekdays item = weekdays.mon; item <= weekdays.sun; ++item) {
Console.WriteLine($"{item} == {(int) item}");
}

但是,在实际应用中,请使用标准 DayOfWeek 枚举

编辑 2:您自己的代码(在问题中)得到改进:

 static void Main(string[] args) {
for (int i = 0; i < 7; i++) { // do not use magic numbers: what does, say, 5 stand for?
// we want weekdays, not int to be printed out
weekdays wd = (weekdays) i;

Console.WriteLine(wd);
}

Console.Read();
}

编辑 3:您自己的代码(在答案中)得到改进:

 // you have to do it just once, that's why pull the line off the loop 
string[] s = Enum.GetNames(typeof(weekdays));

// do not use magic numbers - 7: what does "7" stands for? -
// but actual value: s.Length - we want to print out all the items
// of "s", i.e. from 0 up to s.Length
for (int i = 0; i < s.Length; i++)
Console.WriteLine(s[i]);

关于c# - 从枚举中打印工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40307063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com