首页 > 解决方案 > Xamarin Studio:System.InvalidOperationException

问题描述

我在 Xamarin Studio 中创建了一个新的 MonoGame iOS 解决方案。之后,我在 Game1.cs 中添加了以下代码:

bool IsiOS = false;    
if (Device.RuntimePlatform == Device.iOS)
   IsiOS = true;

但是我在构建项目时收到一条错误消息。

if (Device.RuntimePlatform == Device.iOS)

System.InvalidOperationException 您必须调用 Xamarin.Forms.Init(); 在使用它之前。

我的代码有什么问题?我不知道我应该添加或更改什么。

代码(Game1.cs):

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Xamarin.Forms;

namespace NewTest.iOS
{
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    bool IsiOS = false;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.IsFullScreen = true;
    }

    protected override void Initialize()
    {  
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        if (Device.RuntimePlatform == Device.iOS)
            IsiOS = true;
    }

    protected override void Update(GameTime gameTime)
    {
        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        graphics.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);

        base.Draw(gameTime);
    }
}
}

代码(程序.cs):

using System;
using Foundation;
using UIKit;

namespace NewTest.iOS
{
[Register("AppDelegate")]
class Program : UIApplicationDelegate
{
    private static Game1 game;

    internal static void RunGame()
    {
        game = new Game1();
        game.Run();
    }

    static void Main(string[] args)
    {
        UIApplication.Main(args, null, "AppDelegate");
    }

    public override void FinishedLaunching(UIApplication app)
    {
        RunGame();
    }
}
}

标签: c#xamarinxamarin.iosmonogame

解决方案


The Device class is part of Xamarin Forms. If you are using Xamarin Forms, then you must initialize it first. That is exactly what the error message is telling you.


推荐阅读