我在从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"]; }
}
}
}
仅在此处出现以下错误:
无法将类型'object'隐式转换为'Microsoft.Xna.Framework.Graphics.Texture2D'。存在显式转换(您是否缺少演员?)
我知道我将它存储在listDictionary中存在问题。我做到了,因为这样我可以立即检索所有必要的信息。我该怎么做呢?
先谢谢,
Mark Dijkema
答案 0 :(得分:3)
ListDictionary不是通用的,因此项目存储为对象。你必须将它们强制转换为你想要的类型:
if(team == "blue") { _texture = (Texture2D)LoadGraphics._blue_turret_hull["graphic"]; }
答案 1 :(得分: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;
}
}