0

我得到了这段代码,虽然它工作正常,但它在代码(st.staff_name == chk)上给了我一个警告(可能是意外的参考比较)。我很困惑为什么会这样。帮助将不胜感激。谢谢你。

    private void buttonCreateSubmit_Click(object sender, EventArgs e)
    {
        Body body = new Body
        {
            body_content = richTextBoxBody.Text
        };

        tnDBase.AddToBodies(body);
        tnDBase.SaveChanges();

        var genid = tnDBase.Genres.Single(g => g.genre_name == comboBoxGenre.Text);

        Article article = new Article()
        {
            article_name = textBoxTitle.Text,
            genre_id = genid.genre_id,
            status_id = 3,
            body_id = body.body_id
        };

        tnDBase.AddToArticles(article);
        tnDBase.SaveChanges();

        if (checkedListBoxWriter.CheckedItems.Count != 0)
        {
            for (int x = 0; x <= checkedListBoxWriter.CheckedItems.Count - 1; x++)
            {
                var chk = checkedListBoxWriter.CheckedItems[x];
                var staf = tnDBase.Staffs.SingleOrDefault(st => st.staff_name == chk);
                WriterLog writerlog = new WriterLog()
                {
                    article_id = article.article_id,
                    staff_id = staf.staff_id
                };
                tnDBase.AddToWriterLogs(writerlog);
                tnDBase.SaveChanges();
            }
        }
    }
4

2 回答 2

2

您收到此警告是因为您将 a 与 astring进行比较object。与所有自定义运算符一样,类型的自定义==运算符string(它比较字符串的,而不是两个字符串是否具有引用相等性,它们可能没有)只能在两个操作数都是string引用时工作。

如果您知道其中的项目CheckedItems将是strings,那么只需将其转换为字符串:

SingleOrDefault(st => st.staff_name == (string)chk);
于 2011-10-29T04:32:10.543 回答
0

我猜它会给您警告,因为您正在使用默认值 var chk = checkedListBoxWriter.CheckedItems[x];并将其与数据库项进行比较。尝试询问特定值var chk = checkedListBoxWriter.CheckedItems[x].Value;或强制 chk 为字符串。

于 2011-10-29T04:37:41.767 回答