Xamarin 函数错误

Xamarin function error

我在启动模拟器时遇到这个错误:

An unhandled exception occured

我尝试过使用委托以各种方式调用函数 ciao。有人可以解释为什么这是错误的吗?

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace Prova
{

    [Activity(Label = "Prova", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {

        Button saved;
        protected override void OnCreate(Bundle bundle)
        {
            saved = FindViewById<Button>(Resource.Id.Saved);
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);
            saved.Click += (object sender, EventArgs e) => {
                ciao(sender, e);
            };
        }

        private void ciao (object sender, EventArgs e)
        {

        }
    }
}

很难确定问题出在哪里,因为您没有包含完整的异常和堆栈跟踪,但我在这里看到的一件事会导致代码失败,那就是您正在尝试拉取在您实际设置视图之前,将按钮移出 UI。 FindViewById() returns 如果找不到视图,则为 null,因此您可能会在尝试附加点击处理程序时遇到 NullReferenceException

您应该将 OnCreate 方法更新为如下所示:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);

    SetContentView(Resource.Layout.Main);

    saved = FindViewById<Button>(Resource.Id.Saved);
    saved.Click += ciao;
}