CS0030:无法转换类型' int'到了布尔'

时间:2016-04-22 19:09:00

标签: c# int boolean

我的代码问题在哪里? 我无法在microsoft visual studio 2015上编译它 谁有人可以帮忙?我应该改变什么,问题在哪里?

private void SelectAll_ItemClick(object sender, ItemClickEventArgs e)
{
  GridColumn column = (GridColumn) e.Item.Tag;
  int dataRowCount = this.gridViewCastles.DataRowCount;
  bool flag1 = true;
  bool flag2 = true;
  this.gridViewCastles.BeginUpdate();
  try
  {
    for (int rowHandle = dataRowCount - 1; rowHandle >= 0; --rowHandle)
    {
      if (flag1)
      {
        flag2 = !(bool) this.gridViewCastles.GetRowCellValue(rowHandle, column);
        flag1 = false;
      }
      this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) (bool) (flag2 ? 1 : 0));
    }
  }
  finally
  {
    this.gridViewCastles.EndUpdate();
  }
}

3 个答案:

答案 0 :(得分:2)

问题在于:(bool) (flag2 ? 1 : 0)。您正在尝试使用显式转换将整数转换为布尔值。

改为使用Convert.ToBooleanConvert.ToBoolean(flag2 ? 1 : 0)。顺便说一句,好像它没那么无用:如果1已经已经true,你为什么要将0转换为false而将flag2转换为bool bool

顺便说一下,现在您应该已经意识到int没有隐式或显式转换为Convert.ToBoolean,反之亦然,您需要使用Convert.ToInt32 / {{1}} ..

答案 1 :(得分:1)

替换:

this.gridViewCastles.SetRowCellValue(rowHandle, column, (object)(flag2);

人:

this.gridViewCastles.SetRowCellValue(rowHandle, column, (object)(bool)(flag2 ? 1 : 0));

答案 2 :(得分:0)

this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) (bool) (flag2 ? 1 : 0));

你想做什么?

Flag2是一个布尔值。 ?:运算符允许您测试布尔条件以选择两个可能的值之一,在您的情况下,0和1.在您的代码中,您尝试将0/1转换为布尔值。使用?:运算符的原因是什么?只需输入:

this.gridViewCastles.SetRowCellValue(rowHandle, column, (object) flag2);