C# checkeditems可能的意外引用比较
我得到了这段代码,虽然它工作得很好,但它在代码上给了我一个警告(可能是意外的引用比较)(st.staff_name==chk)。我不明白这是为什么。我们将不胜感激。多谢各位C# checkeditems可能的意外引用比较,c#,winforms,linq,checkedlistbox,C#,Winforms,Linq,Checkedlistbox,我得到了这段代码,虽然它工作得很好,但它在代码上给了我一个警告(可能是意外的引用比较)(st.staff_name==chk)。我不明白这是为什么。我们将不胜感激。多谢各位 private void buttonCreateSubmit_Click(object sender, EventArgs e) { Body body = new Body { body_content = richTextBoxBody.Text
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();
}
}
}
private void按钮创建提交\u单击(对象发送者,事件参数e)
{
车身=新车身
{
body\u content=richTextBoxBody.Text
};
tnDBase.AddToBodies(主体);
tnDBase.SaveChanges();
var genid=tnDBase.Genres.Single(g=>g.genre\u name==comboxgenre.Text);
第条=新条款()
{
article_name=textBoxTitle.Text,
generid\u id=genid.generid\u id,
状态_id=3,
body\u id=body.body\u id
};
tnDBase.AddToArticles(文章);
tnDBase.SaveChanges();
如果(checkedListBoxWriter.CheckedItems.Count!=0)
{
对于(int x=0;x st.staff_name==chk);
WriterLog WriterLog=新WriterLog()
{
article\u id=article.article\u id,
staff_id=staf.staff_id
};
tnDBase.AddToWriterLogs(writerlog);
tnDBase.SaveChanges();
}
}
}
您收到此警告是因为您正在将字符串
与对象
进行比较。与所有自定义运算符一样,字符串
类型的自定义==
运算符(它比较字符串的值,而不是比较两个字符串是否具有引用相等性,它们可能不具有引用相等性)只能在两个操作数都是字符串
引用时工作
如果您知道CheckedItems
中的项目将是string
s,则只需将其转换为字符串:
SingleOrDefault(st => st.staff_name == (string)chk);
我猜它是在警告您,因为您使用的是
var chk=checkedListBoxWriter.CheckedItems[x]
并将其与数据库项进行比较。尝试并请求一个特定的值var chk=checkedListBoxWriter.CheckedItems[x].value代码>或强制chk为字符串