查找谓词 DayOfWeek Issue c#

Find predicate DayOfWeek Issue c#

最近我遇到了一个问题,当我试图在 DayOfWeek 的列表中找到特定的一天时,它在星期日的效果不佳,但在其他所有日子都有效。

我做了一个谓词,但是当我在一个空列表或一个不包含星期日的列表中寻找星期日时,它找到了它。

示例:

namespace testing1
{
    public partial class Timer : Form
    {
        public static List<dayOfWeek> day = new List<dayOfWeek>();//I can set things in it

        public Timer()
        {
            InitializeComponent();
        }

        private void Timer_Load(object sender, EventArgs e)
        {
                Console.WriteLine(day.Count); //return 0 when I instantiate the form without inserting from an another form.

                checkBox1.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Monday; }) == dayOfWeek.Monday; // return false OK
                checkBox2.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Tuesday; }) == dayOfWeek.Tuesday; // return false OK
                checkBox3.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Wednesday; }) == dayOfWeek.Wednesday; // return false OK
                checkBox4.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Thursday; }) == dayOfWeek.Thursday; // return false OK
                checkBox5.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Friday; }) == dayOfWeek.Friday; // return false OK
                checkBox6.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Saturday; }) == dayOfWeek.Saturday; // return false OK
                checkBox7.Checked = day.Find((dayOfWeek d) => { return d == dayOfWeek.Sunday; }) == dayOfWeek.Sunday; // return true WTF ????
        }
    }
}

需要我帮忙吗?

DayOfWeek是一个enum因此它是值类型,值类型变量不能有空值,除非标记为Nullable<>,这意味着很可能[中的第一个值=11=] enumSunday 这将是默认值,所以每当 Find 找不到该值时,它 returns 默认值在这种情况下是 星期日 .

您应该改用 Contains

day.Contains(DayOfWeek.Sunday);
//..

枚举是值类型,Find 扩展方法在处理这种类型的列表时具有以下行为(引自 MSDN):

When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate. Otherwise, there is no way to distinguish between a default value indicating that no match was found and a list element that happens to have the default value for the type. If the default value satisfies the search predicate, use the FindIndex method instead.