匹配具有相同实例名称的2个不同对象

时间:2013-03-01 00:17:55

标签: c# .net

我想知道是否可以将对象与实例名称匹配。

我得到了:

class AnimatedEntity : DrawableEntity
{
    Animation BL { get; set; }
    Animation BR { get; set; }
    Animation TL { get; set; }
    Animation TR { get; set; }
    Animation T { get; set; }
    Animation R { get; set; }
    Animation L { get; set; }
    Animation B { get; set; }

    Orientation orientation ;

    public virtual int Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        //draw depends on orientation
    }
}

enum Orientation { 
    SE, SO, NE, NO, 
    N , E, O, S, 
    BL, BR, TL, TR, 
    T, R, L, B 
}

Orientation是Enum,动画是一个类。

我可以使用相同名称从方向调用正确的动画吗?

2 个答案:

答案 0 :(得分:3)

不是将Animations存储在属性中,而是使用字典怎么样?

Dictionary<Orientation, Animation> anim = new Dictionary<Orientation, Animation> {
    { Orientation.BL, blAnimation },
    { Orientation.BR, brAnimation },
    { Orientation.TL, tlAnimation },
    { Orientation.TR, trAnimation },
    { Orientation.T, tAnimation },
    { Orientation.R, rAnimation },
    { Orientation.L, lAnimation },
    { Orientation.B, bAnimation }
};

然后,您可以使用anim[orientation]访问相应的动画。

答案 1 :(得分:1)

确实Dictionary是一个不错的选择。如果动画将从外部设置,它甚至可以有Animation索引:

class AnimatedEntity : DrawableEntity
{
    Dictionary<Orientation, Animation> Animations { get; set; }

    public AnimatedEntity()
    {
        Animations = new Dictionary<Orientation, Animation>();
    }

    public Animation this[Orientation orientation] 
    { 
        get{ return Animations[orientation]; }
        set{ Animations[orientation] = value;}
    }

    Orientation Orientation { get; set; }

    public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
    {
        Animation anim = Animations[Orientation];
    }
}

将被用作:

AnimatedEntity entity = new AnimatedEntity();
entity[Orientation.B] = bAnimation;
entity[Orientation.E] = eAnimation;
entity[Orientation.SE] = seAnimation;
相关问题