为什么 IS 运算符在 false 时输入 IF 语句?

why does the IS operator enters an IF statement when false?

我最想错过的是这里,
在我制作的调试会话图像中看到。

根据调试器,

(items[i] is MailItem) 为 FALSE,但它仍然进入 if 语句。
我在这里错过了什么?
.

作为参考,这里是这个方法的完整代码

private MailItem GetMailBySubject(DateTime dateReceived, string subject)
{
    MailItem Result = null;

    Microsoft.Office.Interop.Outlook.Application OutlookIns = new Microsoft.Office.Interop.Outlook.Application();
    Microsoft.Office.Interop.Outlook.NameSpace olNamespace = OutlookIns.GetNamespace("MAPI");
    MAPIFolder myInbox = olNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);


    Items items = myInbox.Items;
    int count = items.Count;
    MailItem mail = null;
    int i = 1; //DO NOT START ON 0

    while ((i < count) && (Result == null))
    {
        if (items[i] is MailItem)
        {
            mail = (MailItem)items[i];
            if ((mail.ReceivedTime.ToString("yyyyMMdd hh:mm:ss") == dateReceived.ToString("yyyyMMdd hh:mm:ss")) && (mail.Subject == subject))
            {
                Result = mail;
            }
        }
        i++;
    }

    return Result;
}

我使用 Wai Ha Lee 提供的 the link 解决了这个问题。不过我不得不改变它,因为测试一个项目是否是 MailItem 仍然表现得很奇怪。

所以我首先将项目复制到一个单独的列表中,并确保该列表中只有 MailItem 类型的项目。
我得到这个过滤的唯一方法是使用 try...catch,我仍然想要更好的方法,我仍然很好奇为什么测试 if (items[i] is MailItem) 表现如此奇怪。

List<MailItem> ReceivedEmail = new List<MailItem>();
foreach (var testMail in items)
{
    try
    {
        ReceivedEmail.Add((MailItem)testMail);
    }
    catch (System.Exception ex)
    {
        ;
    }
}

之后我可以使用列表 ReceivedEmail 而无需检查 MailItem。

This 所以答案解释了为什么你看到 IF 条件得到通过,即使它里面的表达式是 false。显然这是调试器和多线程的问题。此外,它还建议使用 lock 来防止此问题的解决方法。希望对你有帮助。