0

我在从 listDictionary 中检索 texture2D 时遇到问题。

这是我的 LoadGraphics 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;

namespace Space_Game
{
    public static class LoadGraphics
    {
        //global variable
        public static ListDictionary _blue_turret_hull;

        public static void LoadContent(ContentManager contentManager)
        {
            //loads all the graphics/sprites
            _blue_turret_hull = new ListDictionary();
            _blue_turret_hull.Add("graphic", contentManager.Load<Texture2D>("Graphics/Team Blue/Turret hull spritesheet"));
            _blue_turret_hull.Add("rows", 1);
            _blue_turret_hull.Add("columns", 11);
        }
    }
}

这是应该检索 Texture2D 的 Turret 类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Space_Game
{
    class Turret_hull:GameObject
    {
        public Turret_hull(Game game, String team)
            : base(game)
        {
            if(team == "blue") { _texture = LoadGraphics._blue_turret_hull["graphic"];      }
        }
    }
}

只有在这里它给出了以下错误:

无法将类型“对象”隐式转换为“Microsoft.Xna.Framework.Graphics.Texture2D”。存在显式转换(您是否缺少演员表?)

我知道我将它存储在 listDictionary 中这一事实存在问题。我这样做了,因为这样我可以一次检索所有必要的信息。我还应该怎么做?

提前致谢,

马克·迪克玛

4

2 回答 2

3

ListDictionary 不是通用的,因此项目存储为对象。您必须将它们转换回您想要的类型:

if(team == "blue") { _texture = (Texture2D)LoadGraphics._blue_turret_hull["graphic"];      }
于 2012-07-09T12:11:32.557 回答
1

实现您想要的更好的方法可能是定义一个具有 3 个属性的新类,并使用它来检索您需要传递的信息:

public class TurretHullInfo
{
    Texture2D Graphic { get; set; }
    int Rows { get; set; }
    int Columns { get; set; }
}

public static class LoadGraphics
{
    //global variable
    public static TurretHullInfo _blue_turret_hull;

    public static void LoadContent(ContentManager contentManager)
    {
        //loads all the graphics/sprites
        _blue_turret_hull = new TurretHull();
        _blue_turret_hull.Graphic = contentManager.Load<Texture2D>("Graphics/Team Blue/Turret hull spritesheet");
        _blue_turret_hull.Rows = 1;
        _blue_turret_hull.Columns = 11;
    }
}

class Turret_hull : GameObject
{
    public Turret_hull(Game game, String team)
        : base(game)
    {
        if(team == "blue")
            _texture = LoadGraphics._blue_turret_hull.Graphic;     
    }
}
于 2012-07-09T12:27:42.923 回答