我需要的是什么代码我应该替换为:<-- code (exist) -->
。
我有一个在表中创建单元格的类。我将这些单元格存储在单元格列表中。
List<Cell> locations = new List<Cell>();
我正试图找出该列表中是否存在一个单元格。我正在执行以下操作:
cell_in_array(new Cell(x, y));
public bool cell_in_array(Cell cell)
{
if(<-- code (exist) -->){
return true;
} else {
return false
}
}
单元类别
public class Cell
{
int x_pos; // column
int y_pos;// row
public Cell(int col, int row)
{
x_pos = col;
y_pos = row;
}
public int getRow()
{
return y_pos;
}
public int getColumn()
{
return x_pos;
}
public int[] position()
{
int[] cell_loc = { x_pos, y_pos };
return cell_loc;
}
}
通过使用的简化使您的生活变得轻松IEqualityComparer<Cell>
。我使用此解决方案是因为您可能需要在某个地方使用这种逻辑。
public class CellComparer : IEqualityComparer<Cell>
{
public bool Equals(Cell x, Cell y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
if (x.Column == y.Column && x.Row == y.Row) return true;
return false;
}
public int GetHashCode(Cell cell)
{
int hCode = cell.Column ^ cell.Row;
return hCode.GetHashCode();
}
}
使用它非常简单,如果您检查列表内容,您将看到它包含两个元素,因为第一个和最后一个添加的单元格相同。
var list = new HashSet<Cell>(new CellComparer());
list.Add(new Cell(0, 1));
list.Add(new Cell(1, 2));
list.Add(new Cell(0, 1));
对HashSet
谁将使用您的表格CellComparer
来避免Cell
重复表示感谢。
因此,请使用自动属性而不是方法来返回字段的值。您的单元格类必须如下所示:
public class Cell
{
public Cell(int col, int row)
{
Column = col;
Row = row;
}
public int Row { get; private set; }
public int Column { get; private set; }
public int[] Position
{
get { return new[] { Column, Row }; }
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句