Skip to main content
 首页 » 编程设计

C#:如果列表框字符串等于

2024年02月23日30虾米哥

如何使用如下的 if 语句?:

 if ( listBox6.SelectedItem.ToString = ("hi"))  
{ 
 
} 

我试过了,但得到了错误:

Cannot assign to 'ToString' because it is a 'method group'

请您参考如下方法:

  1. Method invocations必须在括号中包含参数列表,即使该列表为空。

  2. equality operator是 ==,不要与 assignment operator 混淆=.

所以你的代码应该是这样的:

if (listBox6.SelectedItem.ToString() == "hi") 
{ 
} 

请注意,如果当前没有选中的项目,listBox6.SelectedItem 将返回 null。在这种情况下调用 ToString 会导致 NullReferenceException在运行时。 cast 可能更安全所选项目改为字符串:

if ((string)listBox6.SelectedItem == "hi") 
{ 
}