启动模拟器时出现此错误:



我尝试使用委托(delegate)以各种方式调用函数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中拉出在实际设置 View 之前。如果找不到该 View ,则FindViewById()返回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;
}

10-08 13:48