比较警告与NullreferenceException

Bue*_*ena 0 c# winforms

foreach (Control c in panPrev.Controls)
{
if (c.Tag == "move")
Run Code Online (Sandbox Code Playgroud)

效果很好,但产生警告:可能的意外参考比较; 得到一个值比较,左侧输入'string'

foreach (Control c in panPrev.Controls)
{
if (c.Tag.ToString() == "move")  // this produce NullReferenceException.
Run Code Online (Sandbox Code Playgroud)

该怎么办?

Kir*_*oll 5

你没有接受警告提出的建议.这将是:

if ((string)c.Tag == "move")
Run Code Online (Sandbox Code Playgroud)

这将在Tagnull 为事件时正常工作,而尝试调用.ToString可能的null引用会打开您所获得的异常.

您需要执行此操作的原因是因为.Tag声明为a object,因此==在a object和a 之间使用运算符string使用引用相等,而将a string与a 进行比较则string使用已实现的==定义的重载string来比较实际值.