作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
作为编程新手,我的问题可能看起来有点基础,我想要的是使用循环或其他方式打印枚举中提到的所有日期。我已经使用了一个控制台应用程序。非常感谢有关提高 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/
我是一名优秀的程序员,十分优秀!