如何使用默认覆盖处理异步和等待

How to handle async & await with default override's

在 Xamarin 项目中,Android - 我是 android 开发新手。在 activity 上工作时,我在 OnCreate 方法中为 ListView.

设置自定义适配器
protected async override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);
    SetContentView(Resource.Layout.Main);

    var listAdapter = new CustomListAdapter(this);
    //.................................................
    listView = (ListView) FindViewById(Resource.Id.list);

    // populate the listview with data
    listView.Adapter = listAdapter;
}

在适配器的 ctor 中,在异步调用中创建项目列表。

public CustomListAdapter(Activity context) //We need a context to inflate our row view from
    : base()
{
    this.context = context;
    // items is List<Product>
    items = await GetProductList();
}

由于 Getproducts 是一个异步调用,它会异步加载数据。

问题是一旦我将适配器设置为列表,它将尝试调用适配器的 GetView 方法。届时,不会加载项目。所以有一个空异常。

如何处理这种情况。

谢谢。

您不能在构造函数中使用 await

您可以改为执行几项操作。在我看来,这里最好的方法是拥有一个单独的异步方法,您可以在创建对象后调用并等待它。

var listAdapter = new CustomListAdapter(this);
await listAdapter.InitializeAsync();

另一种选择是将构造函数设为私有并使用异步静态方法创建实例并对其进行初始化:

public static async Task<CustomListAdapter> CustomListAdapter.CreateAsync(Activity context)
{
    var listAdapter = new CustomListAdapter(context);
    listAdapter.items = await GetProductList();
    return listAdapter;
}

也许重写 getCount,这样如果 items 仍然是 null 或者 items 有零个项目 return listView 大小应该是 0。

public int getCount() {
    return items != null ? items.size() : 0;
}