修饰符静态对C#中的此项错误无效

时间:2016-06-29 17:13:39

标签: c# android azure xamarin.android xamarin.forms

我正在尝试使用Xamarin表单中的Azure通知中心实现推送通知。目前我正在使用GCM执行此操作,并按照this link进行操作。但是在“将推送通知添加到droid项目”教程的第5步中,我收到modifier static is not valid for this item的错误。完成此步骤后,这就是我的代码:

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

        // Create a new instance field for this activity.
        static MainActivity instance = null;
        // Set the current instance of MainActivity.
        instance = this;

        global::Xamarin.Forms.Forms.Init (this, bundle);
        Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
        LoadApplication (new App ());
        try
        {
            // Check to ensure everything's setup right
            GcmClient.CheckDevice(this);
            GcmClient.CheckManifest(this);

            // Register for push notifications
            System.Diagnostics.Debug.WriteLine("Registering...");
            GcmClient.Register(this, PushHandlerBroadcastReceiver.SENDER_IDS);
        }
        catch (Java.Net.MalformedURLException)
        {
            CreateAndShowDialog("There was an error creating the Mobile Service. Verify the URL", "Error");
        }
        catch (Exception e)
        {
            CreateAndShowDialog(e.Message, "Error");
        }
        private void CreateAndShowDialog(String message, String title)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.SetMessage(message);
        builder.SetTitle(title);
        builder.Create().Show();
    }
    // Return the current activity instance.
    public static MainActivity CurrentActivity
    {
        get
        {
            return instance;
        }
    }
}

我是C#和Xamarin表格的新手,无法弄清楚我哪里出错了。

2 个答案:

答案 0 :(得分:2)

您需要在函数外部声明静态变量。

private static MainActivity instance = null;
// Return the current activity instance.
public static MainActivity CurrentActivity
{
    get
    {
        return instance;
    }
}

然后只需在instance = this;OnCreate

答案 1 :(得分:0)

问题是您正在尝试在方法内创建静态变量。如果再看一下该链接中的示例,您会注意到该变量在方法之外。