【问题标题】:Swift extension with inheritance to c# extension methods?继承到 c# 扩展方法的 Swift 扩展?
【发布时间】:2020-10-12 09:20:08
【问题描述】:

我正在尝试将一段 Swift 代码转换为 c#。

我知道 c# 方法扩展,但在这种情况下,swift 代码继承了一个类:

extension ViewController: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return characters.count
  }
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.text = characters[indexPath.row]
    return cell
  }
}

在 c# 中可以做到这一点吗?

编辑:代码来自here

编辑 2:在 Xamarin docs 中找到 solution

【问题讨论】:

  • 不,Swift 扩展更强大。但这听起来像是一个 XY 问题。为什么要尝试将表格视图代码转换为 C#?您是否可能使用 Xamarin.iOS 或其他东西?
  • UITableViewDataSource 不是一个类,而是一个协议,所以这个扩展声明了协议的一致性,而不是继承。
  • 确实我正在使用 Xamarin.iOS 并尝试转换 this sample
  • @DávidPásztor 那将是 c# 中的一个接口

标签: c# xamarin.ios uikit


【解决方案1】:

Xamarin.iOS 基于 Objective-C,与 swift 会有一些不同。在您的情况下,您似乎想要实现 UITableViewDataSource ,对吗?如果是这样,您可以检查以下代码

1。创建 UITableViewSource 的子类

public class MyTableSource : UITableViewSource {

    string[] characters;
    string CellIdentifier = "TableCell";

    public TableSource (string[] items)
    {
        characters = items;
    }

    public override nint RowsInSection (UITableView tableview, nint section)
    {
        return characters.Length;
    }

    public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier);
        string item = characters[indexPath.Row];

        //if there are no cells to reuse, create a new one
        if (cell == null)
        { 
            cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); 
        }

        cell.TextLabel.Text = item;

        return cell;
    }
}

2 。在 ViewController 中

var TableView = new UITableView(View.Bounds); 
string[] tableItems = new string[] {"111","222","333","444","555","666"};
table.Source = new MyTableSource(tableItems);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    • 1970-01-01
    • 2012-12-17
    相关资源
    最近更新 更多