如果其他xamarin iOS优化条件

时间:2014-08-23 12:11:40

标签: c# ios optimization xamarin

如何优化tableview单元格颜色的if else条件

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){

    var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
    if (cell == null)
        cell = new TableCell ();
        cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;

    if (indexPath.Row % 2 == 0) {
            cell.BackgroundColor = UIColor.White;
        }   else {
            cell.BackgroundColor = UIColor.LightGray;
    }}

2 个答案:

答案 0 :(得分:3)

这里几乎没有什么可以优化的。我唯一要改变的是最后if - 我用条件表达式替换它:

public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath){
    var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell;
    if (cell == null) {
        cell = new TableCell ();
    }
    cell.Accessory = UITableViewCellAccessory.DisclosureIndicator;
    cell.BackgroundColor = (indexPath.Row % 2 == 0) ? UIColor.White : UIColor.LightGray;
}

这是个人偏好的问题:您的if语句包含两个作业也非常易读。

答案 1 :(得分:0)

你也可以用??用于细胞创建:

var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell ?? new TableCell();

从外观上看,这也可能是一个小小的改进,因为附件似乎是静态类型,不需要每次都分配:

var cell = tableView.DequeueReusableCell (TableCell.Key) as TableCell 
    ?? new TableCell() { Accessory = UITableViewCellAccessory.DisclosureIndicator };