我有以下代码,它会发出警告“可能的非预期参考比较;要进行值比较,请将右侧投射到string
类型”:
// oControl is of type Control
if ((ocontrol.Name == oDataRowView["ConName"].ToString()))
{
//Do stuff
}
else
{
//Do other Stuff
}
我尝试使用以下各项修复它,但我仍然收到警告
if ((ocontrol.Name == Convert.ToString(oDataRowView["ConName"])))
{
//Do stuff
}
else
{
//Do other Stuff
}
if ((ocontrol.Name == (string)oDataRowView["ConName"]))
{
//Do stuff
}
else
{
//Do other Stuff
}
请有人解释一下我仍然会收到警告的原因以及处理此问题的最佳做法吗?
答案 0 :(得分:0)
这些选项可行:
if (Equals(ocontrol.Name, oDataRowView["ConName"])) // likely best option
if ((string)ocontrol.Name == oDataRowView["ConName"].ToString()) // assuming neither item is null
if (ocontrol.Name as string == oDataRowView["ConName"] as string) // assuming second item is actually a string